首页 > 解决方案 > 如何使用opencv单独裁剪蒙版区域?

问题描述

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

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

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()但自动运行(无需手动单击和拖动)并且可以裁剪多个区域的东西。任何想法或提示表示赞赏。谢谢

标签: pythonopencv

解决方案


对于red,您可以选择 HSV 范围(0,50,20) ~ (5,255,255)(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

在此处输入图像描述

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


推荐阅读