在MATLAB中在图像中绘制黑色矩形

时间:2016-03-28 07:01:15

标签: matlab

我遇到了问题。我正在编写一个脚本,并希望将此效果应用于白色图像。

enter image description here

但现在我的图像显示为这样。

enter image description here

我坚持这个我写两个for循环一个用于行,第二个用于根据图像大小800x450绘制黑色线条的列但是我如何绘制黑盒子。

脚本:

        clear all;
        close all;
        clc;
        image = rgb2gray(imread('4.jpg'));
        b = cast(image,'double');
        out = 60*((b)./(max(max(b))));

        out = out + 195;

        [r,c,d] = size(out);

        x = floor(r/80);

        y = floor(c/160);

        %x rows
        for i = 1 : 88 : 450
            %  replaceable line
            out(i:i+x,:,:) = 0;

        end



        %y columns
        for i = 1 : 88 : 800
            %  replaceable line
            out(:,i:i+y,:) = 0;
        end

        final = cast(out,'uint8');

        imshow(final);

3 个答案:

答案 0 :(得分:0)

绘制棋盘的技巧是找到x和y指数(加在一起时)是奇数或偶数的情况。

sz = size(img);
[row, col] = ndgrid(1:sz(1), 1:sz(2));
checkers = logical(mod(row + col, 2));

或更简单

checkers = bsxfun(@(x,y)mod(x + y, 2), 1:size(img, 1), (1:size(img, 2)).').';

这将返回一个带有0(黑色)和1(白色)检查器的矩阵。

enter image description here

如果你想改变棋子的大小,你可以做这样的事情。

sz = size(img);
checkersize = 10;
[row, col] = ndgrid(1:sz(1), 1:sz(2));
checkers = logical(mod(ceil(row / checkersize) + ceil(col/checkersize)),2);

或者只是

checkersize = 10;
checkers = bsxfun(@(x,y)mod(ceil(x/checkersize) + ceil(y/checkersize), 2), 1:size(img, 1), (1:size(img, 2)).').';

enter image description here

如果您确实要将此效果应用于图片,可以使用上面的checkers矩阵索引图片并设置值similar to this answer

replacementColor = [0 0 0];                         % RGB
reshaped_image = reshape(img, [], 3);               % Flatten first two dims
C = repmat(replacementColor, [sum(checkers(:)), 1]);% Make color correct size
reshaped_image(checkers, :) = C;                    % Replace color
newImage = reshape(reshaped_image, size(img));      % Shape it back into original

答案 1 :(得分:0)

您可以使用以下代码:

image = ones(450,800,3);%create white image
[row_len,column_len,rgb] = size(image);
side_vert = floor(row_len/5);
side_hor  = floor(column_len/9);
color = 1;
for(i = 1:side_vert:row_len)
    for(j = 1:side_hor:column_len - side_hor)
        if(color == 0)
            image(i:side_vert - 1 + i,j:j + side_hor - 1,:) = 0;
            color = 1;
        else
            color = 0;
        end;
    end;
end;
imshow(image);

答案 2 :(得分:0)

您还可以使用checkerboard功能:

k = 30;   %// size of each square in the checkerboard
img = checkerboard(k) < 0.5;   

由于某种原因,该功能会使棋盘的一半变灰,因此您必须使用< 0.5(或> 0.5,具体取决于您想要的顺序)才能为您提供黑白图像。

enter image description here

相关问题