how to change the color of an image in a 400x500 pixel rectangle in matlab

To change the color of an image in a 400x500 pixel rectangle in Matlab, you can use the following code:

main.m
% Read the image from the file
img = imread('image.jpg');

% Define the rectangle area
x1 = 100;
y1 = 100;
x2 = 500;
y2 = 400;

% Extract the rectangle from the image
rectImg = img(y1:y2, x1:x2, :);

% Change the color of the rectangle
redVal = 255; % define the new value of red color
greenVal = 0; % define the new value of green color
blueVal = 0; % define the new value of blue color

% Get the size of the rectangle
[height, width, ~] = size(rectImg);

% Loop through each pixel in the rectangle and set the new color
for y = 1:height
    for x = 1:width
        rectImg(y, x, 1) = redVal; % set the new red value
        rectImg(y, x, 2) = greenVal; % set the new green value
        rectImg(y, x, 3) = blueVal; % set the new blue value
    end
end

% Put the modified rectangle back into the image
img(y1:y2, x1:x2, :) = rectImg;

% Show the resulting image
imshow(img);
878 chars
35 lines

In this code, we first read the image from a file using the imread function. Next, we define the rectangle area using the x1, y1, x2, and y2 variables. We then extract the rectangle from the image using img(y1:y2, x1:x2, :).

To change the color of the rectangle, we define new values for the red, green, and blue color channels using the redVal, blueVal, and greenVal variables. We then use a nested loop to loop through each pixel in the rectangle and set the new color values.

Finally, we put the modified rectangle back into the original image using img(y1:y2, x1:x2, :) = rectImg and then display the resulting image using the imshow function.

gistlibby LogSnag