如何从二进制图像中获取矩形?

时间:2018-04-11 08:40:20

标签: opencv image-processing artificial-intelligence

我有二进制图像,例如enter image description here

我想从白色区域获得一个包含所有白色区域的矩形。任何帮助,提前谢谢

2 个答案:

答案 0 :(得分:1)

这里我使用findContours和approxPoly: Result

这里是我写的快速代码:

img =  cv2.imread("rectangle.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,0)
_, contours,hierarchy = cv2.findContours(thresh.astype(np.uint8), 1, 2)
cnt = contours[0]

epsilon = 0.05*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt, epsilon,True)

mask = np.zeros_like(thresh)
for i in range(len(approx)-1):
    start = tuple(approx[i][0])
    end = tuple(approx[i+1][0])
    cv2.line(mask,start,end,255,2)

start = tuple(approx[-1][0])
end = tuple(approx[0][0])
cv2.line(mask,start,end,255,2)

答案 1 :(得分:0)

如果你不想找一个真正的矩形:

Result

img =  cv2.imread("rectangle.jpg")
plt.imshow(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,0)
_, contours,hierarchy = cv2.findContours(thresh.astype(np.uint8), 1, 2)
cnt = contours[0]

epsilon = 0.05*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt, epsilon,True)

hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)

mask = np.zeros_like(thresh)
for i in range(defects.shape[0]):
    s,e,f,d = defects[i,0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv2.line(img,start,end,[255,0,0],2)
    #cv2.circle(img,far,5, [255,0,0],-1)



cv2.imwrite("img_semRect.png", img)
plt.imshow(img)
相关问题