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

To change the color of a specific rectangle in an image in MATLAB, you can follow these steps:

  1. Read the image using the imread function and store it in a variable, say img.
  2. Display the image using the imshow function.
  3. Create a rectangle using the rectangle function and set its Position property to the dimensions of the rectangle you want to modify. You can also set other properties such as EdgeColor and FaceColor to define the appearance of the rectangle.
  4. Use the imcrop function to crop out the rectangular region from the original image.
  5. Change the color of the cropped region as desired.
  6. Use the imwrite function to save the modified image to a file.

Here's the MATLAB code that implements these steps:

main.m
% read the image
img = imread('myimage.jpg');

% display the image
imshow(img);

% define the dimensions of the rectangle to be modified
rect_pos = [100 100 400 500];

% create a rectangle with red color and thick edges
rectangle('Position', rect_pos, 'EdgeColor', 'r', 'LineWidth', 3);

% crop out the rectangular region
rect_region = imcrop(img, rect_pos);

% change the color of the cropped region to green
green_region = rect_region;
green_region(:,:,1) = 0;
green_region(:,:,2) = 255;
green_region(:,:,3) = 0;

% copy the modified rectangular region back into the original image
img(rect_pos(2):rect_pos(2)+rect_pos(4)-1, rect_pos(1):rect_pos(1)+rect_pos(3)-1, :) = green_region;

% save the modified image to a file
imwrite(img, 'modified_image.jpg');
758 chars
27 lines

Note that in this example, I've changed the color of the cropped region to green by setting the green channel to its maximum value while setting the red and blue channels to zero. You can modify these values as desired to achieve your desired color.

gistlibby LogSnag