图像中的区域识别

时间:2017-03-18 16:10:48

标签: python opencv computer-vision

我有这个形象。 Image of a map

我想: - 1.识别此图像中的所有区域 2.确认哪个区域与其他区域相连

我的目标是在此图像中应用四色定理并输出正确着色的图像。我是python和opencv的初学者。

非常感谢您对此事的帮助。

1 个答案:

答案 0 :(得分:0)

这是一个MATLAB代码,可以满足您的需求。在Python + OpenCV中实现它不应该太复杂:

% read image
m = rgb2gray(imread('map.jpg')); 
% remove noise
m = medfilt2(m);
b = m < 250;
se1 = strel('disk',1,0);
se2 = ones(7);
b = imclose(imopen(b,se1),se2);
% skeletonize
B = bwmorph(b,'skel',inf);
% remove background
R = padarray(~B,[1 1],1);
bg = bwselect(R,1,1,4);
R(bg) = 0;
R = R(2:end-1,2:end-1);
% get regions connected components
ccRegions = bwconncomp(R,4);
maskRegions = false([size(R),ccRegions.NumObjects]);
MAP = zeros(size(R));
% generate a binary mask for each region, dilate it to detect overlaps
% between neigbors
for ii = 1:ccRegions.NumObjects
    maskRegions((ii - 1)*numel(R) + (ccRegions.PixelIdxList{ii})) = 1;
    maskRegions(:,:,ii) = imdilate(maskRegions(:,:,ii),se1);
    MAP(maskRegions(:,:,ii)) = ii;
end
% detect neighbors using masks overlapping
neighborsRegions = cell(ccRegions.NumObjects,1);
for ii = 1:ccRegions.NumObjects
    r = repmat(maskRegions(:,:,ii),[1 1 ccRegions.NumObjects]);
    idxs = any(any(r & maskRegions,1),2); %indexes of touching neighbors
    idxs(ii) = 0; % remove self index
    neighborsRegions{ii} = find(idxs);
end
% show result
imshow(MAP,[])
c = regionprops(ccRegions,'Centroid');
for ii = 1:ccRegions.NumObjects
    text(c(ii).Centroid(1),c(ii).Centroid(2),num2str(ii),'FontSize',20,'Color','r');
end

输出如下:enter image description here

每个地区的邻居都是:

neighborsRegions = {[2;3]
                    [1;3;4]
                    [1;2;4;5;6]
                    [2;3;6]
                    [3;6]
                    [3;4;5]
                    []}