How do I edit a cropped part of an image and put it back in its original place?

4 views (last 30 days)
So essentially what I am trying to do is edit only one part of an image in matlab. More specifically I want to take a part of a binary image assign a color to only the white section of that part, and then place the edited part back into the original image. I am having a lot of trouble with this. I can crop the image and edit it but I can't figure out how to put it back into place. Any help is appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Mar 2017
Example:
img = randi([0 1], 480, 720); %create an image
X = 100; Y = 125; W = 300; H = 147; %where are we cropping?
part_img = imcrop(img, [X, Y, W, H]); %crop part out
mask = part_img == 1; %select the white
R = part_img;
G = part_img;
B = part_img
R(mask) = 0.8; %recolor white as [0.8, 0.25, 0.573]
G(mask) = 0.25;
B(mask) = 0.573;
part_img_color = cat(3, R, G, B); %now you have a full-color image ready to be put back
img_color = img(:,:,[1 1 1]); %you cannot put a color image inside grayscale, promote original to color
img_color(Y:Y+H-1, X:X+W-1, :) = part_img_color; %store the partial image back
Notice that X becomes columns and Y becomes rows in that last line
  2 Comments
Walter Roberson
Walter Roberson on 18 Oct 2017
Someone pointed out that this code gives a subscript dimension error. I have traced that back to imcrop giving a size 1 larger than expected, an aspect that I would call a bug. As perhaps someday Mathworks might fix that problem, I will not compensate by adjusting the width specifications, and will instead compensate by using the size actually extracted. The last line should then be:
img_color(Y:Y+size(part_image,1)-1, X:X+size(part_image,2)-1, :) = part_img_color; %store the partial image back

Sign in to comment.

More Answers (1)

YVAN N
YVAN N on 18 Oct 2017
i get the error : Subscripted assignment dimension mismatch.

Community Treasure Hunt

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

Start Hunting!