简体   繁体   中英

how to find coordinates of the rectangles from image in python with opencv?

I have some imperfect rectangles in the image, I need set of coordinates for each rectangle in python using opencv

I have tried Canny edge detection and the used findContours but it's giving more coordinates than required because rectangles are not having straight lines

I have read similar questions but I am not getting correct results. Can you please provide solution with code?

original image原来的 After Canny edge detection Canny 边缘检测

How to get only inner borders of rectangles from Canny Edges? As there is double border for each rectangles, it's giving more number of rectangles than required.

image = cv2.imread(OUTPUT_FILE)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.blur(gray, (5,5))

kernel = np.ones((5, 5), np.uint8)
closing = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)

edged = cv2.Canny(closing, 30, 200)
cv2.imshow("Canny", edged)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

print(len(contours))

for c in contours:
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)

    for p in box:
        pt = (p[0],p[1])
        plt.scatter(p[0],p[1])

plt.show()

I think that this problem could be solved using findContours(), depending on your version of OpenCV, it returns several values, but one of them is always contours , which is a list of all points of contour. One bit of advice that I often use is that I calculate the centroid of all contour points. That means that I sum all points along x coordinate sum them and divide by the length of the contour list for this specific contour , and do the same for y coordinate.

You can also use boundingRect() function, which will give you x,y coordinates of top left corner of the bounding box, as well as its width and height. In a link above, you can find a really nice tutorial on the topic. I think that this function suits better to your problem.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM