gpt4 book ai didi

python - 如何使用 OpenCV ConnectedComponents 获取图像

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:08 31 4
gpt4 key购买 nike

如何使用Python OpenCV ConnectedComponents函数获取图像?

通过搜索过去的一些问题,我只能找到如何用不同颜色遮蔽连接的对象(我测试过并且有效,但我不知道标签是如何工作的)
来自这些先前回答的问题的引用:Stackoverflow question 48303309Stackoverflow question 46441893

使用这段代码,我可以获得阴影输出

import cv2
import numpy as np

img = cv2.imread('eGaIy.jpg', 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
ret, labels = cv2.connectedComponents(img)

# Map component labels to hue val
label_hue = np.uint8(179*labels/np.max(labels))
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

# set bg label to black
labeled_img[label_hue==0] = 0

cv2.imshow('labeled.png', labeled_img)
cv2.waitKey()

Original Shaded

有什么方法可以从图像中取出连接的对象吗?
所以输出将是来自原始图像的多个图像

最佳答案

image = cv2.imread('image.png', cv2.IMREAD_UNCHANGED);
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# getting mask with connectComponents
ret, labels = cv2.connectedComponents(binary)
for label in range(1,ret):
mask = np.array(labels, dtype=np.uint8)
mask[labels == label] = 255
cv2.imshow('component',mask)
cv2.waitKey(0)

# getting ROIs with findContours
contours = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
for cnt in contours:
(x,y,w,h) = cv2.boundingRect(cnt)
ROI = image[y:y+h,x:x+w]
cv2.imshow('ROI', ROI)
cv2.waitKey(0)

cv2.destroyAllWindows()

关于python - 如何使用 OpenCV ConnectedComponents 获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51523765/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com