Processing images and counting with MATLAB is executed by executing the commands below in the MATLAB command window.
Processing images and counting with MATLAB
If your computer doesn't have Matlab yet, get it now and install the latest version of Matlab here: Download Matlab
Step 1: Read Image
An image will have significant contrast with its background to identify objects. The imread function reads the image from a specified location and saves it in the matrix img1. The imshow function will display the image.
img1=imread('Lines.jpg');
imshow(img1)
Step 2: Convert Image to Grayscale
This step will remove colors from the image to make object identification easier. The rgb2gray function converts the colors in the image to grayscale and stores it in the matrix img2.
img1=rgb2gray(img1);
imshow(img1)
Step 3: Image Thresholding
Thresholding the image by converting the grayscale image to a binary image containing only two colors. The im2bw() function assigns black color to all pixels with brightness higher than the threshold level, and white otherwise. The graythresh() function computes the threshold level of the image.
img2=im2bw(img1,graythresh(img1));
imshow(img2)
Step 4: Image Enhancement
Utilize the ~ operator to enhance the image. This converts white arrays to black and vice versa. If you want to highlight objects with white color, you can perform this step.
img2=~img2;
imshow(img2)
Step 5: Finding Object Boundaries
This step is to find the boundaries of each object that Matlab detects and stores in B. The text function will print the number of objects that the bwboundaries function finds.
B = bwboundaries(img2);
imshow(img2)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(B))))
hold on
Step 6: Draw Object Boundaries
Image processing and counting with MATLAB is quite interesting, where you can mark the boundaries of objects identified by the bwboundaries function. If you find it too complex, you can skip this step:
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
end
Step 7: Code
img1=imread('Lines.jpg');
imshow(img1)
img1=rgb2gray(img1);
imshow(img1)
img2=im2bw(img1,graythresh(img1));
imshow(img2)
img2=~img2;
imshow(img2)
B = bwboundaries(img2);
imshow(img2)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(B))))
hold on
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
end
So in the article on Mytour, they just guided you through image processing and counting with MATLAB. To improve your Matlab skills, quickly master this program, you can download self-study Matlab course and swiftly enhance your Matlab skills. If you have any questions or areas you don't understand, feel free to leave your comments below the article!
