[英]How to separate objects on their color?
这里不需要真正的颜色检测,因为处理是在cv2.watershed
的输出上cv2.watershed
。 这是一个np.int32
类型的“图像” markers
,值为0, 1, 2, 3, ...
用于cv2.watershed
检测到的单个标记,而0
是背景。 因此,除了迭代所有标记值(假设为i
),屏蔽markers == i
的部分,并找到边界矩形的相应坐标,将该部分复制到新图像并将其保存到某个文件之外,别无他法.
这是一些代码,其中cv2.watershed
是通过相应地使用cv2.findContours
和cv2.drawContours
来模仿的(关于这个问题的有趣部分只是第二个for
循环):
import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage import io # Only needed for web grabbing images
# Load some image with circles from web
image = io.imread('https://www.teachertoolsinc.com/images/detailed/26/TCR77379.png')
plt.figure(1), plt.imshow(image), plt.title('original image'), plt.tight_layout()
# Mimic watershed result using findContours and drawContours
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
gray = cv2.threshold(gray, 16, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
markers = np.zeros_like(gray).astype(np.int32)
for i, cnt in enumerate(cnts):
markers = cv2.drawContours(markers, [cnt], -1, i+1, cv2.FILLED)
plt.figure(2), plt.imshow(markers), plt.title('markers'), plt.colorbar(), plt.tight_layout()
plt.show()
# Assuming we only have markers now; iterate all values and crop image part
for i in np.arange(1, np.max(markers[:, :])+1):
pixels = np.array(np.where(markers == i)).astype(np.int32)
x1 = np.min(pixels[1, :])
x2 = np.max(pixels[1, :])
y1 = np.min(pixels[0, :])
y2 = np.max(pixels[0, :])
cv2.imwrite(str(i) + '.png', image[y1:y2, x1:x2, :])
这是输入图像:
那是模仿的markers
“图像”(参见所提供的图像):
而且,这里有两个切圆:
希望有帮助!
-----------------------
System information
-----------------------
Python: 3.8.1
Matplotlib: 3.2.0rc1
NumPy: 1.18.1
OpenCV: 4.1.2
-----------------------
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.