我有一个带有黑色背景的灰度图像,上面有一些非黑色对象,如下所示:
现在我想找到每个对象的最小(矩形)边界框。如果有帮助的话,我可以在每个对象内提供一个起点。
由于没有花哨的阈值或任何东西,我想避免像 Canny 这样的东西来找到轮廓。如果像素不为 0,则它位于 Blob 中。
最佳答案
为了在图像中任何不完全黑色的地方绘制矩形,您可以执行以下操作:
imagefile = '/path/to/your/image'
img = cv2.imread(imagefile)
# Convert you image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Threshold the image to extract only objects that are not black
# You need to use a one channel image, that's why the slice to get the first layer
tv, thresh = cv2.threshold(gray[:,:,0], 1, 255, cv2.THRESH_BINARY)
# Get the contours from your thresholded image
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
# Create a copy of the original image to display the output rectangles
output = img.copy()
# Loop through your contours calculating the bounding rectangles and plotting them
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(output, (x,y), (x+w, y+h), (0, 0, 255), 2)
# Display the output image
plt.imshow(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))
关于c# - 图像中 Blob 的边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65395239/