如何在opencv中根据深度颜色分割连接区域 [英] how to segment the connected area based on depth color in opencv
问题描述
我有一张,我需要将图片分成8个块.
I have a picture like , which i need to segment the picture into 8 blocks.
我已经尝试过此阈值方法
I have tried this threshold method
img_gray = cv2.imread(input_file,cv2.IMREAD_GRAYSCALE)
ret,thresh = cv2.threshold(img_gray,254,255,cv2.THRESH_BINARY) =
kernel = np.array(cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), (-1, -1)))
img_open = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2.imshow('abc',img_open)
ret1,thresh1 = cv2.threshold(img_open,254,255,cv2.THRESH_BINARY_INV) #
contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP ,cv2.CHAIN_APPROX_NONE)
for i in range(len(contours)):
if len(contours[i]) > 20:
x, y, w, h = cv2.boundingRect(contours[i])
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
print (x, y),(x+w, y+h)
阈值之后
最终结果是一些连接在一起的块形成了一个很大的段,这不是我希望的.其他解决方法
the end result is some blocks connected together are formed into a large segment, which is not what I hoped. Any other ways to get it around
推荐答案
我将尝试为您提供一种基于深度梯度将汽车分开的算法的示意图.las,仅查看大深度梯度的轮廓,轿厢就无法完美分离,因此,需要对边界轮廓进行一些细化".轮廓完成后,简单的连接零部件群集就足以将轿厢分开.
I'll try and give you a sketch of an algorithm that separates the cars based on depth gradients. Alas, simply looking at the contour of large depth gradients, the cars are not perfectly separated, therefore, some "refinement" of the boundary contour is required. Once the contours are complete, a simple connected component clustering is sufficient to separate the cars.
这是我的代码(在Matlab中,但我可以肯定,找到与opencv等效的函数并不太复杂):
Here's my code (in Matlab, but I'm quite certain it's not too complex to find opencv equivalent functions):
img = imread('http://i.stack.imgur.com/8lJw8.png'); % read the image
depth = double(img(:,:,1));
depth(depth==255)=-100; % make the background VERY distinct
[dy dx] = gradient(depth); % compute depth gradients
bmsk = sqrt(dx.^2+dy.^2) > 5; % consider only significant gradient
% using morphological operations to "complete" the contours around the cars
bmsk = bwmorph( bwmorph(bmsk, 'dilate', ones(7)), 'skel');
% once the contours are complete, use connected components
cars = bwlabel(~bmsk,4); % segmentation mask
st = regionprops(cars, 'Area', 'BoundingBox');
% display the results
figure;
imshow(img);
hold all;
for ii=2:numel(st), % ignore the first segment - it's the background
if st(ii).Area>200, % ignore small regions as "noise"
rectangle('Position',st(ii).BoundingBox, 'LineWidth', 3, 'EdgeColor', 'g');
end;
end;
输出为
还有
不够完美,但可以带给您足够的距离.
Not perfect, but brings you close enough.
进一步阅读:
-
bwmorph
:执行形态学操作. -
bwlabel
:输出连接的组件的分段蒙版(标记). -
regionprops
:计算统计信息(例如,区域和边界框).
考虑到这一点,深度具有如此出色的渐变,您可以对深度渐变进行阈值处理并获得良好的连接组件.
Coming to think of it, depth has such nice gradients, you can threshold the depth gradient and get nice connected components.
这篇关于如何在opencv中根据深度颜色分割连接区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!