We will again work using my_image.bmp
. Let's see if we can write a script that whitens a 30 x 40 rectangular area on the top-left corner of the image and blackens a 40 x 50 rectangular area at the bottom-right corner of the image. We can manage to do so, if we follow these steps:
img = imread('my_image.bmp'),
255
. Let's keep the original image so that we can compare it to the final result. This will be achieved using the following line of code:img_final = img; img_final(1:30,1:40) = 255;
end
as follows:img_final(end-39:end,end-49:end) = 0;
subplot(1,2,1) imshow(img) title('Original image') subplot(1,2,2) imshow(img_final) title('Processed image')
RectangleBrightness
(as before, the extension .m
will be added by Editor).>> RectangleBrightness
The result should be something like the following image:
First of all, congratulations! You just wrote and executed your first script that alters pixel values. The commands used were not something new, but they were all executed as a batch for an image this time, producing the final result you just saw. The method used for the alteration of the pixel values was indexing, since we said that it is preferable than using for loops
.
To select the rectangles to be altered, we had to define the top and bottom row indices and the left and right column indices. The top-left rectangle was defined in a rather intuitive manner. We used index 1
for both the top row and the left column. The indices for the bottom row and the right column were set to 30
and 40
respectively.
The tricky part was selecting the indices that should be used for the bottom-right rectangle. Again, we knew the height and width, but we should use it with respect to the height and width of the image. However, altering the width and height values for each new image would be highly impractical. This is why we used the very convenient index keyword end
, which denoted the maximum valued index for each dimension. When it is used for rows, it automatically takes the value of the maximum number of rows, and when it is used for columns it takes the maximum number of columns. In our case we used it in both positions, to calculate the proper top row index (end-39
) and bottom row index (end
), and also to calculate the proper left column index (end-49
) and right row index (end
).