change grayscale pixel color by xy coordinates

I have a piece of code that returns the x and y coordinates of a rectangle that I draw on a grayscale image.
frameA=read('abc.jpg');
imshow(frameA);
H=imrect;
Position = wait(H);
Position contains [x y h w], where x,y = xy coordinates of top left corner of rectangle, h=rectangle height, w =rectangle width. So I have all the coordinates I need.
How can I use these coordinates to modify the color of the pixels in this rectangle?
If I use frameA(x,y) = 1 for instance, the x,y here corresponds to the indices of the pixels and not their spatial coordinates.

 Akzeptierte Antwort

Image Analyst
Image Analyst am 4 Aug. 2015

0 Stimmen

With frameA() you need to pass in the row and column, in that order, not x and y in that order. So you'd need frameA(y, x) but even then you'd need to convert y and x to integers because you can't have fractional values: frameA(round(y), round(x)).
To set the values in the rectangle to a particular gray scale, you do something like this
[rows, columns, numberOfColorChannels] = size(frameA);
if numberOfColorChannels > 1
% Convert to grayscale if it's color.
frameA = rgb2gray(frameA);
end
col1 = round(Position(1));
col2 = round(col1 + Position(3));
row1 = round(Position(2));
row2 = round(row1 + Position(4));
frameA(row1:row2, col1:col2) = desiredGrayLevel;

5 Kommentare

v10as
v10as am 4 Aug. 2015
Thanks! I have one follow-up question.
How can I change the pixel color to Red?
You need to use a real true color RGB image. Then you have 3 color channels you need to change where you make the red channel 255 and the green and blue channels 0. Then recombine:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Make red channel 255
redChannel(row1:row2, col1:col2) = 255;
% Make green and blue channels 0
greenChannel(row1:row2, col1:col2) = 0;
greenChannel(row1:row2, col1:col2) = 0;
% Recombine separate color channels into a single, true color RGB image.
rgbImage = cat(3, redChannel, greenChannel, blueChannel);
v10as
v10as am 4 Aug. 2015
So it is not possible to change the pixel color on a grayscale image, to red?
I actually have a video that I am reading in frames and I need to have a little red mark to identify a particular location in the video. Is it possible to do this any other way?
If it's gray scale, you can only display it as red via a colormap. To make it really red, it has to be a 3D RGB image.
To indicate some point with a red mark over an image, you can use plot()
imshow(grayImage);
hold on;
plot(column, row, 'r.', 'Markersize', 30);
v10as
v10as am 5 Aug. 2015
That was extremely helpful! Thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Gefragt:

am 4 Aug. 2015

Kommentiert:

am 5 Aug. 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by