2

We are using the below image and we tried extracting the border coordinates using contours of opencv

def apply_contours(image,img):
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # print(f"Total number of contours found = {str(len(contours))}")
    # get area of every contour
    
    contour_bboxes = list(map(lambda a : cv2.boundingRect(a), contours))
    contours_area = list(map(lambda a : area_rectangle(a) ,contour_bboxes))
    
    # make area and index as list
    list_of_areas = []
    for index,j in enumerate(contours_area):
        list_of_areas.append([index,j])
    # sort the max area contours in reverse (desc) order and pick top 3
    list_of_areas = sorted(list_of_areas, key = lambda x: x[1],reverse=True)
    
    list_bboxes = list_of_areas[:20]
    sep_contours = [contours[i[0]] for i in list_bboxes]
    contour_bboxes = list(map(lambda a : cv2.boundingRect(a), sep_contours))
    
    
#     cv2.imwrite("Centriolds.png",image_)
    x = find_independent_conoturs(contour_bboxes)
    print(x)
    
    image_ = image.copy()
    for i in x:
        pt1 = (i[0],i[1])
        pt2 = (i[0]+i[2],i[1]+i[3])
        color = (0,255,0)
        thickness = 2
        cv2.rectangle(image_,pt1, pt2,color, thickness)
    cv2.imshow('independent Contours', image_)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    print("Total independent contours ",len(x))
    
    list_of_areas = list_of_areas[:len(x)]
    # get contours based on index
    list_of_contours = [contours[i[0]] for i in list_of_areas]
    # draw contours
    get_cords = lambda x: [list(i[0]) for i in x]
    cordinates_request = []
    for i in list_of_contours:
        cordinates_request.extend(get_cords(i))
    
    print(f"total edges {len(cordinates_request)}")
#     print(cordinates_request)
    
#     cordinates_request = sorted(cordinates_request, key = lambda x: x[1])
    df = convert_to_df(cordinates_request)
    blank_img = np.zeros(image.shape, dtype=np.uint8)
    
    cv2.drawContours(image, list_of_contours, -1, (0, 255, 0), 1)
    cv2.imshow('Contours', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite(os.path.join(path_,"Image.png"),image)
    return image,df

Where we are using this code and can achieve the exact points please refer the overlapped image below.

But, when we export these coordinates and try to plot on illustration image these coordinates are not overlapping. how do we achieve this in python?

Drawing Image:

Drawing image

Highlighted Image:

Highlighted

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
  • Could you explain why these contours are not what you expected? They seem well aligned to me. Also, what is `find_independent_conoturs`? – Cris Luengo Jul 31 '21 at 14:20

0 Answers0