2

I have an image in matlab read in from a movie file. The image is a 3d array. How would I go through that image and if the colors are mostly red(eg. red>200 blue<50 green<50) make that part of the image black and ther other areas white?

Eventually I would like to do this for the whole video, but I need to understand this first!

Matt Le Fleur
  • 2,311
  • 25
  • 37
  • similar question: http://stackoverflow.com/questions/4063965/how-can-i-convert-an-rgb-image-to-grayscale-but-keep-one-color/ – Amro Jun 22 '11 at 14:53

2 Answers2

1
img = imread('image.jpg');
r = img(:,:,1);
g = img(:,:,2);
b = img(:,:,3);
iR = r > 200;
iG = g < 50;
iB = b < 50;
img2 = 255*ones([size(img,1) size(img,2)],'uint8');
img2(iR & iG & iB) = 0;

subplot(2,1,1), imshow(img)
subplot(2,1,2), imshow(img2)

enter image description here

For memory and speed issues, you can replace the related lines as follows:

img2 = true([size(img,1) size(img,2)]);
img2(iR & iG & iB) = false;
petrichor
  • 6,249
  • 4
  • 33
  • 48
  • Thankyou for this! Just one more thing now that I see how you have done this. Could you suggest any way of applying this to a whole movie file? Would you have to read the movie frame by frame, apply this to all the frames and then join them together into another movie? – Matt Le Fleur Jun 22 '11 at 11:43
  • @Phoen1xUK: I added a solution to show how to apply this to a whole movie matrix – Amro Jun 22 '11 at 15:23
  • @Phoen1xUK: Amro's solution may help you if your video' size is not so large. But if you want to process videos that are to large to fit in memory, you might check VideoReader(http://www.mathworks.com/help/techdoc/import_export/f5-132080.html#f5-146610) to load the required portion of the video to memory and process it as in Amro's solution or frame by frame. – petrichor Jun 23 '11 at 10:25
0

The basic case of a single RGB image (3D-matrix) has been shown by others:

img = imread('image.png');     %# some RGB image

img2 = ~(img(:,:,1)>200 & img(:,:,2)<50 & img(:,:,3)<50);

If you want to apply this to all frames of a movie (4D-matrix = height-by-width-by-color-by-frame), try the following compact solution:

mov = cat(4, img, img);        %# a sample video of two frames

mov2 = squeeze( ~(mov(:,:,1,:)>200 & mov(:,:,2,:)<50 & mov(:,:,3,:)<50) );
Community
  • 1
  • 1
Amro
  • 121,265
  • 25
  • 232
  • 431