![](/img/trans.png)
[英]How to crop regions of interest in an image using bounding box coordinates?
[英]Minimum Bounding Box for image regions?
我找到了一種方法來計算圖像上封閉區域的最小邊界框(還考慮旋轉角度)。
我可以使用以下代碼來提取此圖像的質心坐標,邊框的寬度和長度以及旋轉角度:
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()
當我在一幅圖像中有很多區域時,我的代碼無法提取所有這些信息。
你能幫我么
cnt = contours[0] # you're only checking the 1st contour here
您可能想遍歷所有找到的輪廓:
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.