我有一张像 这样的图片,我需要将图片分割成 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)
阈值处理后
最后的结果是一些 block 连在一起形成了一个大段,这不是我所希望的。 任何其他解决方法
我将尝试为您提供一个基于深度梯度分离汽车的算法草图。 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;
输出是
和
不完美,但足够接近。
进一步阅读:
想到这一点,深度有很好的梯度,你可以阈值深度梯度并得到很好的连通分量。
我是一名优秀的程序员,十分优秀!