如何根据opencv中的深度颜色分割连接区域

use*_*624 5 opencv image-processing computer-vision image-segmentation

我有一张照片 在此输入图像描述,我需要将图片分成8个块.

我试过这个阈值方法

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)
Run Code Online (Sandbox Code Playgroud)

在阈值之后
在此输入图像描述

最终的结果是连接在一起的一些块形成了一个大段,这不是我所希望的. 在此输入图像描述 在此输入图像描述 在此输入图像描述 任何其他方式来解决它

Sha*_*hai 4

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

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

img = imread('https://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;
Run Code Online (Sandbox Code Playgroud)

输出是

在此输入图像描述

在此输入图像描述

不完美,但让你足够接近。

进一步阅读:

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

想想看,深度具有如此好的梯度,您可以对深度梯度进行阈值并获得良好的连接组件。