简体   繁体   English

图像区域的最小边界框?

[英]Minimum Bounding Box for image regions?

I found a way to compute minimum bounding box for closed regions on image (considering also rotation angle). 我找到了一种方法来计算图像上封闭区域的最小边界框(还考虑旋转角度)。

I can extract coordinates of centroid, width and length of bounding box and rotation angle for this image using this piece of code: 我可以使用以下代码来提取此图像的质心坐标,边框的宽度和长度以及旋转角度:

from PIL import Image
import cv2
import numpy as np
from matplotlib import pyplot as plt

image_file = Image.open("binaryraster.png")
image_file = image_file.convert('1')
image_file.save('result.png')

img = cv2.imread('result.png',0)
edges = cv2.Canny(img,100,200)
plt.subplot(111),plt.imshow(edges,cmap = 'gray')
plt.title('Canny Edge detection'), plt.xticks([]), plt.yticks([])

ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]


leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)



M = cv2.moments(cnt)
centroid_x = int(M['m10']/M['m00'])
centroid_y = int(M['m01']/M['m00'])

print (leftmost)
print (rightmost)
print (topmost)
print (bottommost)

print(centroid_x)
print(centroid_y)

print(rect)
print(box)

plt.show()

When I have many regions inside one image my code fails to extract all this information. 当我在一幅图像中有很多区域时,我的代码无法提取所有这些信息。

can you please help me 你能帮我么

cnt = contours[0] # you're only checking the 1st contour here

you probably want to loop over all found contours: 您可能想遍历所有找到的轮廓:

for cnt in contours:

    leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
    rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
    topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
    bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

    rect = cv2.minAreaRect(cnt)
    box = cv2.cv.BoxPoints(rect)
    box = np.int0(box)



    M = cv2.moments(cnt)
    centroid_x = int(M['m10']/M['m00'])
    centroid_y = int(M['m01']/M['m00'])

    print (leftmost)
    print (rightmost)
    print (topmost)
    print (bottommost)

    print(centroid_x)
    print(centroid_y)

    print(rect)
    print(box)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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