您可以应用霍夫变换来检测网格线。一旦我们有了这些,您就可以推断出网格位置和旋转角度:
%# load image, and process it
img = imread('print5.jpg');
img = imfilter(img, fspecial('gaussian',7,1));
BW = imcomplement(im2bw(img));
BW = imclearborder(BW);
BW(150:200,100:150) = 0; %# simulate a missing chunk!
%# detect dots centers
st = regionprops(BW, 'Centroid');
c = vertcat(st.Centroid);
%# hough transform, detect peaks, then get lines segments
[H,T,R] = hough(BW);
P = houghpeaks(H, 25);
L = houghlines(BW, T, R, P);
%# show image with overlayed connected components, their centers + detected lines
I = imoverlay(img, BW, [0.9 0.1 0.1]);
imshow(I, 'InitialMag',200, 'Border','tight'), hold on
line(c(:,1), c(:,2), 'LineStyle','none', 'Marker','+', 'Color','b')
for k = 1:length(L)
xy = [L(k).point1; L(k).point2];
plot(xy(:,1), xy(:,2), 'g-', 'LineWidth',2);
end
hold off
(我正在使用imoverlay
文件交换中的功能)
结果:
这是累加器矩阵,其中与检测到的线对应的峰值突出显示:
现在我们可以通过计算检测到的线的平均斜率来恢复旋转角度,过滤到两个方向之一(水平或垂直):
%# filter lines to extract almost vertical ones
%# Note that theta range is (-90:89), angle = theta + 90
LL = L( abs([L.theta]) < 30 );
%# compute the mean slope of those lines
slopes = vertcat(LL.point2) - vertcat(LL.point1);
slopes = atan2(slopes(:,2),slopes(:,1));
r = mean(slopes);
%# transform image by applying the inverse of the rotation
tform = maketform('affine', [cos(r) sin(r) 0; -sin(r) cos(r) 0; 0 0 1]);
img_align = imtransform(img, fliptform(tform));
imshow(img_align)
这是旋转回来的图像,以便网格与 xy 轴对齐: