裁剪特定的颜色区域Python + OpenCV

问题描述

enter image description here

我无法裁剪图像上的粉红色线条。理想情况下,我想把它裁剪成整个粉红色,如果包括蓝色就可以了。

我做了什么

import cv2
import numpy as np 
from PIL import Image,ImageFilter

#convertes image to hsv and applies blur
img = cv2.imread("1501.jpg")
hsv = cv2.cvtColor(img,cv2.COLOR_RGB2RGB)
fin = cv2.GaussianBlur(hsv,(25,25),cv2.BORDER_DEFAULT)

#divided the image in half to see the target
na = np.array(fin)
orig = na.copy()
m = orig.shape[0]
n = orig.shape[1]/2
M = int(m)
N = int(n)
tiles = [orig[x:x+M,y:y+N] for x in range(0,orig.shape[0]) for y in range(0,orig.shape[1],N)]
variable = tiles[0]
Image.fromarray(variable).save('variable.jpg')

#extracts color from the target
hsv_lower = (300,2.2,71)
hsv_upper = (326,41,32.5)
mask = cv2.inRange(variable,hsv_lower,hsv_upper)

下一步做什么 我不确定接下来要做什么,也不确定我是否一开始就捕捉到了粉红色线。首选 python3 解决方案。

解决方法

您可以使用 findContours 来分割阈值 blob。

阈值图像:

enter image description here

按大小过滤轮廓:

enter image description here

裁剪轮廓:

enter image description here

我不知道为什么输出图像中的颜色是蓝色。如果其他人知道为什么会发生这种情况,我很想知道,因为这让我有点发疯。

代码:

import cv2
import numpy as np

# load image
img = cv2.imread("band.jpg");

# rescale
scale = 0.25;
h,w = img.shape[:2];
h = int(h*scale);
w = int(w*scale);
img = cv2.resize(img,(w,h));

# hsv
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV);
h,s,v = cv2.split(hsv);

# thresh
thresh = cv2.inRange(h,140,160);

# contours
_,contours,_ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE);

# filter contours by size
big_cntrs = [];
marked = img.copy();
for contour in contours:
    area = cv2.contourArea(contour);
    if area > 10000:
        print(area);
        big_cntrs.append(contour);
cv2.drawContours(marked,big_cntrs,-1,(0,255,0),3);

# create a mask of the contoured image
mask = np.zeros_like(h);
mask = cv2.drawContours(mask,-1);

# crop out
out = np.zeros_like(img) # Extract out the object and place into output image
out[mask == 255] = img[mask == 255];

# show
cv2.imshow("Original",img);
cv2.imshow("thresh",thresh);
cv2.imshow("Marked",marked);
cv2.imshow("out",out);
cv2.waitKey(0);

# save
cv2.imwrite("thresh.png",thresh);
cv2.imwrite("marked.png",marked);
cv2.imwrite("out.png",out);

编辑:

修复蓝色问题(改为“mask = np.zeros_like(h);”)。

我使用的是 OpenCV 3.4.2