How can I draw a triangle in an image in MATLAB?
I need to draw a triangle in an image I have loaded. The triangle should look like this:
1 0 0 0 0 0
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 1 0 0
1 1 1 1 1 0
1 1 1 1 1 1
But the main problem I have is that I do not know how I can create a matrix like that. I want to multiply this matrix with an image, and the image开发者_Go百科 matrix consists of 3 parameters (W, H, RGB).
You can create a matrix like the one in your question by using the TRIL and ONES functions:
>> A = tril(ones(6))
A =
1 0 0 0 0 0
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 1 0 0
1 1 1 1 1 0
1 1 1 1 1 1
EDIT: Based on your comment below, it sounds like you have a 3-D RGB image matrix B
and that you want to multiply each color plane of B
by the matrix A
. This will have the net result of setting the upper triangular part of the image (corresponding to all the zeroes in A
) to black. Assuming B
is a 6-by-6-by-3 matrix (i.e. the rows and columns of B
match those of A
), here is one solution that uses indexing (and the function REPMAT) instead of multiplication:
>> B = randi([0 255],[6 6 3],'uint8'); % A random uint8 matrix as an example
>> B(repmat(~A,[1 1 3])) = 0; % Set upper triangular part to 0
>> B(:,:,1) % Take a peek at the first plane
ans =
8 0 0 0 0 0
143 251 0 0 0 0
225 40 123 0 0 0
171 219 30 74 0 0
48 165 150 157 149 0
94 96 57 67 27 5
The call to REPMAT replicates a negated version of A
3 times so that it has the same dimensions as B
. The result is used as a logical index into B
, setting the non-zero indices to 0. By using indexing instead of multiplication, you can avoid having to worry about converting A
and B
to the same data type (which would be required to do the multiplication in this case since A
is of type double
and B
is of type uint8
).
精彩评论