您可以找到所有绿色像素,找到轮廓,并裁剪找到的轮廓的边界矩形:
凝胶图像中的所有绿色像素,其中 RGB = (0, 255, 0):
green_pix = np.all(img == (0, 255, 0), 2)
将 green_pix 转换为uint8
值为 0 和 255 的二进制图像:
thresh_gray = green_pix.astype(np.uint8)*255
在 中查找轮廓thresh_gray
:
contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
获取矩形,并裁剪矩形
out = img[y:y+h, x:x+w, :]
这是一个工作代码示例:
import numpy as np
import cv2
# (cv_major_ver, cv_minor_ver, cv_subminor_ver) = (cv2.__version__).split('.') # Get version of OpenCV
img = cv2.imread('green_box.png')
# Gel all green pixels in the image - where RGB = (0, 255, 0)
green_pix = np.all(img == (0, 255, 0), 2)
# Convert green_pix to uint8 binary image with values 0 and 255
thresh_gray = green_pix.astype(np.uint8)*255
# Find contours in thresh_gray.
# if int(cv_major_ver) < 4:
# _, contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# else:
# contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2] # Shortcut (get index [-2] instead of using if-else).
# Get rectangle (assume there is only one contour)
x, y, w, h = cv2.boundingRect(contours[0])
# Crop rectangle
out = img[y:y+h, x:x+w, :]
cv2.imwrite('out.png', out) #Save out to file (for testing).
# Show result (for tesing).
cv2.imshow('out', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
我有一个更简单的解决方案:
这是代码:
# Find indices of green pixels.
idx = np.where(np.all(img == (0, 255, 0), 2))
# Get minimum and maximum index in both axes (top left corner and bottom right corner)
x0, y0, x1, y1 = idx[1].min(), idx[0].min(), idx[1].max(), idx[0].max()
# Crop rectangle
out = img[y0:y1+1, x0:x1+1, :]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句