可以使用Matlabs内置的棋盘方法
detectCheckerboardPoints
和
checkerboard
找到棋盘的大小并构造一个新的大小合适的棋盘。由于只能存在两个可能的棋盘,请同时构建这两个棋盘,并检查哪一个棋盘最匹配。
img = imread('PNWSv.jpg'); %Load image
%Prepare image
I = rgb2gray(img);
I2 = imerode(I,strel('square',10));
bw = imbinarize(I2,'adaptive');
%Find checkerboard points
[imagePoints,boardSize] = detectCheckerboardPoints(bw);
%Find the size of the checkerboard fields
x = boardSize(2)-1;
y = boardSize(1)-1;
fields = cell(y,x);
for k = 1:length(imagePoints)
[i,j] = ind2sub([y,x],k);
fields{i,j} = imagePoints(k,:);
end
avgDx = mean(mean(diff(cellfun(@(x) x(1),fields),1,2)));
avgDy = mean(mean(diff(cellfun(@(x) x(2),fields),1,1)));
%Construct the two possibilities
ref1 = imresize(imbinarize(checkerboard),[avgDx,avgDy]*8);
ref2 = imcomplement(ref1);
%Check which ones fits the better
c1 = normxcorr2(ref1,I);
c2 = normxcorr2(ref2,I);
if max(c2(:))<max(c1(:))
ref=ref1;
c = c1;
else
ref=ref2;
c = c2;
end
%Plot the checkerboard bounding box on top of the original image
[ypeak, xpeak] = find(c==max(c(:)));
yoffSet = ypeak-size(ref,1);
xoffSet = xpeak-size(ref,2);
imshow(img);
imrect(gca, [xoffSet+1, yoffSet+1, size(ref1,2), size(ref1,1)]);