如何使用opencv单独裁剪蒙版区域?

时间:2019-07-16 17:15:39

标签: python opencv

我有许多不同颜色(红色,绿色,黄色,紫色等)的一堆圆圈的图像。我想单独裁剪所有红色圆圈并将其保存为单独的文件(例如circle(1).png,circle(2).png等)。

到目前为止,我只有一个显示红色圆圈的解决方案。我使用cv2.inRange创建了一个蒙版,并使用了cv2.bitwise _ and仅显示红色圆圈。这是我的代码:

import cv2 
import numpy as np


image = cv2.imread('dots.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

lower_red = np.array([150,100,0])
upper_red = np.array([255,255,255])

 # Threshold the HSV image to get only red cirlces
mask = cv2.inRange(hsv, lower_red, upper_red)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(image,image, mask=mask)

我猜我正在寻找类似cv2.selectROI()的东西,但是它会自动运行(无需手动单击并拖动)并且可以裁剪多个区域。任何想法或技巧表示赞赏。谢谢

1 个答案:

答案 0 :(得分:1)

对于red,您可以使用here给定的(0,50,20) ~ (5,255,255)选择HSV范围(175,50,20)~(180,255,255)colormap。例如,上面代码中的遮罩将无法检测到下面图像中的两个红色圆圈。自己检查一下。

您可以尝试以下代码:

import cv2 
import numpy as np

image = cv2.imread('circles.jpg')
img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Gen lower mask (0-5) and upper mask (175-180) of RED
mask1 = cv2.inRange(img_hsv, (0,50,20), (5,255,255))
mask2 = cv2.inRange(img_hsv, (175,50,20), (180,255,255))

# Merge the mask and crop the red regions
mask = cv2.bitwise_or(mask1, mask2)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(image,image, mask=mask)

# coverting image with red colored region of interest from HSV to RGB
hsv2bgr = cv2.cvtColor(res, cv2.COLOR_HSV2BGR)

# RGB to GRAYSCALE
rgb2gray = cv2.cvtColor(hsv2bgr, cv2.COLOR_BGR2GRAY)

# Applying thresholding to the grayscale image for black & white color
thresh_gray = cv2.threshold(rgb2gray, 20,255, cv2.THRESH_BINARY)[1]

# Find the different contours
contours = cv2.findContours(rgb2gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]
#print(len(contours))

i = 0
for c in contours:
    _, radius = cv2.minEnclosingCircle(c)

    if radius>10:
        # create a mask and fill it with white color
        mask = np.zeros(image.shape, dtype=np.uint8)
        cv2.fillPoly(mask, pts=[c], color=(255, 255, 255))

        # Bitwise-AND mask and original image 
        # output is red circle with black background
        masked_image = cv2.bitwise_and(image, mask)

        # to get individual red circle with white background
        mask_ = cv2.bitwise_not(mask) 
        circle_ = cv2.bitwise_or(masked_image, mask_)

        cv2.imwrite('circle({}).jpg'.format(i), circle_)
        i+=1

输入图像: circles.jpg

enter image description here

上面的输入图像中有两个红色圆圈对象,因此它将创建两个文件circle(0).jpgcircle(1).jpg,每个文件都有单独的红色圆圈。