很遗憾,我认为没有内置解决方案可以解决您的问题,但我已经开发了一些代码来帮助您解决此问题,但不幸的是,它需要图像处理工具箱才能很好地与代码配合使用。正如您的 cmets 中提到的,您已经有了这个,所以我们应该没问题。
这背后的逻辑比较简单。我们将假设您的前后图片大小相同,并且共享相同数量的通道。第一部分是声明一个空白图像,我们在一定厚度的中间画一条直线。这背后的复杂性在于声明一个比图像的原始大小略大的图像。原因是因为我要在中间画一条线,然后将这个空白图像旋转一定角度,以达到你想要的第一部分。我将使用imrotate 将图像旋转您想要的任何角度。第一个直觉是声明一个与原件大小相同的图像,在中间画一条线并旋转它。但是,如果你这样做,你最终会断开线,而不是从图像的顶部到底部绘制。这是有道理的,因为在某个角度上绘制的线比垂直绘制时覆盖的像素更多。
使用勾股定理,我们知道可以在图像上绘制的最长线是对角线。因此,我们在rows 和cols 是原始图像的行和列的行和列中声明一个图像为sqrt(rows*rows + cols*cols)。之后,我们将采取天花板以确保我们已经尽可能多地覆盖,并且我们增加了一些额外的空间以适应线条的宽度。我们在此图像上画一条线,旋转它,然后我们将裁剪图像,使其与输入图像的大小相同。这样可以确保以您希望的任何角度绘制的线从上到下完全绘制。
这个逻辑是最难的部分。一旦你这样做了,你声明了两个logical 掩码,你使用imfill 将掩码的左侧填充为一个掩码,我们将反转掩码以找到另一个掩码。您还需要使用我们之前使用imrotate 创建的线条图像来索引掩码并将值设置为false,以便我们忽略线条上的这些像素。
最后,您获取每个蒙版、索引到您的图像并复制您想要的图像的每个部分。您最终使用线条图像来索引输出并将值设置为白色。
废话不多说,代码如下:
% Load some example data
load mandrill;
% im is the image before
% im2 is the image after
% Before image is a colour image
im = im2uint8(ind2rgb(X, map));
% After image is a grayscale image
im2 = rgb2gray(im);
im2 = cat(3, im2, im2, im2);
% Declare line image
rows = size(im, 1); cols = size(im, 2);
width = 5;
m = ceil(sqrt(rows*rows + cols*cols + width*width));
ln = false([m m]);
mhalf = floor(m / 2); % Find halfway point width wise and draw the line
ln(:,mhalf - floor(width/2) : mhalf + floor(width/2)) = true;
% Rotate the line image
ang = 20; % 20 degrees
lnrotate = imrotate(ln, ang, 'crop');
% Crop the image so that it's the same dimensions as the originals
mrowstart = mhalf - floor(rows/2);
mcolstart = mhalf - floor(cols/2);
lnfinal = lnrotate(mrowstart : mrowstart + rows - 1, mcolstart : mcolstart + cols - 1);
% Make the masks
mask1 = imfill(lnfinal, [1 1]);
mask2 = ~mask1;
mask1(lnfinal) = false;
mask2(lnfinal) = false;
% Make sure the masks have as many channels as the original
mask1 = repmat(mask1, [1 1 size(im,3)]);
mask2 = repmat(mask2, [1 1 size(im,3)]);
% Do the same for the line
lnfinal = repmat(lnfinal, [1 1 size(im, 3)]);
% Specify output image
out = zeros(size(im), class(im));
out(mask1) = im(mask1);
out(mask2) = im2(mask2);
out(lnfinal) = 255;
% Show the image
figure;
imshow(out);
我们得到:
如果您希望线朝另一个方向移动,只需将角度 ang 设为负值即可。在上面的示例脚本中,我将角度逆时针设置了 20 度(即正)。要重现您给出的示例,请指定 -20 度。我现在得到这张图片: