python - 如何使用opencv单独裁剪掩模区域?

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

最佳答案

对于红色,您可以选择 HSV 范围 (0,50,20) ~ (5,255,255)(175,50,20)~( 180,255,255) 使用给定的颜色图 here 。例如,上面代码中的蒙版不会检测到下图中的两个红色圆圈。你自己检查一下。

您可以尝试以下代码:

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 每个带有单独的红色圆圈。

关于python - 如何使用opencv单独裁剪掩模区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062432/

相关文章:

image - 形态学操作将线条与图片边缘合并

python - 通过广播减去 numpy 中每一行的平均值

python - cmake、swig 和 python : How to override conflicting symbols

python - 不会将csv数据存储到mysql表中吗?

c - 在 pkg-config 搜索路径中找不到包 gtk-engines-2

opencv - 使用 openCV 检测图像中部分被遮挡的矩形

python - Opencv Python程序

python - 在 Python 中打开 mha 图像文件(2015 brats 挑战数据集)

python - 如何使用 Python 的 Click 包从装饰器返回参数值?

python - 使用鼠标事件绘制模糊的矩形