gpt4 book ai didi

opencv - 如何在opencv中根据深度颜色分割连通区域

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:29 24 4
gpt4 key购买 nike

我有一张像 enter image description here 这样的图片,我需要将图片分割成 8 个 block 。

这个阈值法我试过

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)

阈值处理后
enter image description here

最后的结果是一些 block 连在一起形成了一个大段,这不是我所希望的。 enter image description here enter image description here enter image description here任何其他解决方法

最佳答案

我将尝试为您提供一个基于深度梯度分离汽车的算法草图。 las,仅仅看大深度梯度的轮廓,汽车并没有完全分开,因此,需要对边界轮廓进行一些“细化”。一旦轮廓完成,一个简单的连接组件聚类就足以分离汽车。

这是我的代码(在 Matlab 中,但我很确定找到 opencv 等效函数并不太复杂):

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;

输出是

enter image description here

enter image description here

不完美,但足够接近。

进一步阅读:

  • bwmorph : 执行形态学操作。
  • bwlabel :输出连接组件的分割掩码(标记)。
  • regionprops : 计​​算图像区域的统计数据(例如面积和边界框)。

想到这一点,深度有很好的梯度,你可以阈值深度梯度并得到很好的连通分量。

关于opencv - 如何在opencv中根据深度颜色分割连通区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45247717/

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