在彩色框中裁剪图像

莫伊斯

我有一个图像如下。我需要将图像的“绿色”框和裁剪部分检测为单独的图像。

我只能使用 numpy & opencv

我看了几个帖子,但我无法弄清楚这一点。任何人都可以帮忙。根据搜索,我猜测需要为此使用某种掩码。如果是,请提供一些有关如何选择特定颜色值的信息。我已经看到颜色值选择本身就是一个很大的话题,但我自己无法弄清楚。我很感激任何指导。

在此处输入图片说明

红色的

您可以找到所有绿色像素,找到轮廓,并裁剪找到的轮廓的边界矩形:

  • 凝胶图像中的所有绿色像素,其中 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章