简体   繁体   English

如何使用Matlab检测局部矩形并对齐图像?

[英]How can I detect a partial rectangle and align image using Matlab?

I was wondering how it would be possible to detect the bottom right corner of a paper square I manually made (which is probably not perfectly a square, because I drew it myself) on top of another object. 我想知道如何才能检测到我手动制作的纸正方形的右下角(可能不是完美的正方形,因为我自己画了它)在另一个对象之上。 What I want to do is use this square as a reference and align the image according to the bottom right corner of the square. 我想要做的是使用这个正方形作为参考,并根据正方形的右下角对齐图像。 I'm quite a Matlab amateur. 我是Matlab的业余爱好者。 Can anybody help? 有人可以帮忙吗?

The top left square is the paper square I need to detect which is the reference point. 左上方的正方形是我需要检测的纸张正方形,它是参考点。

左上角带有正方形的示例图像

You have a lot of choices to detect the square; 您有很多选择来检测正方形。 it's actually a rectangle; 它实际上是一个矩形; you want to detect, but the easiest way is using morphological operations. 您想要检测,但是最简单的方法是使用形态学运算。 Here I provided a commented script to help you; 在这里,我提供了一个注释脚本来帮助您; since you are a MATLAB amateur. 因为您是MATLAB的业余爱好者。

ShowMaskAsOverlay is not a built-in command in MATLAB, though, It is very useful. ShowMaskAsOverlay不是MATLAB中的内置命令,它非常有用。 If you want to download it visit this link . 如果要下载,请访问此链接

Another way I would suggest from what I understood from your question. 根据您对问题的了解,我会提出另一种建议。 You can save the image before making the square, and save another image after making the square. 您可以在制作正方形之前保存图像,在制作正方形之后保存其他图像。 Then you will only need to get the difference between the two images. 然后,您只需要获取两个图像之间的差异即可。

close all;clear all;clc;

% Read in Image
im = imread('stack.png');

[r, c, ch] = size(im);

% Convert Image to Gray if it's RGB
if ch == 3
    gray = rgb2gray(im);
end

% Threshold Value; > 0.87 = 1 and  < 0.87 = 0
thresh = 0.87;
bw = im2bw(gray, thresh);

% Removing unwanted white pixels
bw = bwareaopen(bw, 400);
bw = imerode(bw, strel('disk', 3));
bw = imfill(bw, 'holes');
bw = bwareaopen(bw, 600);
bw = imdilate(bw, strel('disk', 3)); %optional. Could be omitted

% Calculating the BoundingBox of the Square
s = regionprops(bw, 'BoundingBox');
box = struct2cell(s);
pos = cell2mat(box);

%% Displaying Images
figure(1)
imshow(im)
rectangle('position', pos, 'edgecolor', 'red', 'linewidth', 1.5)
str = ['Bounding Box Bottom Right Corner Coordinate Value = ', num2str(pos(4))];
h = text(pos(3), pos(4), num2str(pos(4)));
set(h, 'Color', 'k', 'FontSize', 12, 'FontWeight', 'bold')
title(str)

figure(2)
imshow(gray)
showMaskAsOverlay(0.5, bw, 'g')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM