how can i convert pixels into cms,the code that is available online is giving error

8 views (last 30 days)
thia is the code that i m using.pixe
cmPerPixel = distanceInCm / distanceInPixels;
% Now to convert a distance.
lengthInCm = lengthInPixels * cmPerPixel
% And to convert an area in pixels to square cm:
areaInSquareCm = areaInPixels * cmPerPixel ^ 2
  7 Comments
Anjaneyulu Bairi
Anjaneyulu Bairi on 6 Jan 2025
@Tejaswi , can you share the correct code which contains "cmPerPixel = distanceInCm / distanceInPixels"?
Thank you
Walter Roberson
Walter Roberson on 6 Jan 2025
From your code, we could plausibly define
distanceInPixels = lengthOfDarkerRed;
However, distanceInCm needs to be defined from external information, possibly together with scale information extracted from the original image (if it has some kind of ruler)

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 6 Jan 2025
You need to define a certain distance in your image to be a specified number of cm. Do you know the field of view? Or the width of some particular object in the image?
See my attached spatial calibration demo and adapt as needed.
  4 Comments
Tejaswi
Tejaswi on 8 Jan 2025
is there a possible way to interact with you one on one just to clarify my problem statement??cause im still getting error in this code,im new to matlab thats why im not able to explain the error very well
Image Analyst
Image Analyst on 10 Jan 2025
Try this:
% Demo by Image Analyst
% Initialization steps:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
markerSize = 20;
%--------------------------------------------------------------------------------------------------------
% READ IN TEST IMAGE
folder = [];
baseFileName = 'frame_0515.jpg';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
%--------------------------------------------------------------------------------------------------------
% Display the image.
subplot(2, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis('on', 'image');
title('Original RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Update the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Maximize window.
g = gcf;
g.WindowState = 'maximized';
g.Name = 'Demo by Image Analyst';
g.NumberTitle = 'off';
drawnow;
%--------------------------------------------------------------------------------------------
% GET THE INDIVIDUAL COLOR CHANNELS AND TAKE THE RED ONE FOR CALIBRATION.
[redChannel, greenChannel, blueChannel] = imsplit(rgbImage);
[tabletMask, cmPerPixel] = CalibrateSpatially(redChannel);
%--------------------------------------------------------------------------------------------
% Show the blue channel image - it will have the highest contrast
% and we will use that image to compute the stain area.
subplot(2, 3, 5);
imshow(blueChannel, [])
impixelinfo;
axis('on', 'image');
caption = sprintf('Blue Channel Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Threshold the blue channel.
% Interactively and visually set a threshold on a gray scale image using Image Analyst's utility.
% https://www.mathworks.com/matlabcentral/fileexchange/29372-thresholding-an-image?s_tid=srchtitle
% stainMask = threshold(0, 60, blueChannel);
% The threshold can be anywhere between 30 and 80 for this image.
stainMask = blueChannel < 60;
% Fill holes and take the largest blob.
stainMask = bwareafilt(imfill(stainMask, 'holes'), 1);
% Show the stain mask image.
subplot(2, 3, 6);
imshow(stainMask)
impixelinfo;
axis('on', 'image');
caption = sprintf('Stain Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
%--------------------------------------------------------------------------------------------
% Measure the stain width and area in pixels
props = regionprops(stainMask, 'Area', 'BoundingBox');
stainAreaInPixels = props.Area
stainWidthInPixels = props.BoundingBox(3)
% Convert to cm and cm^2
stainAreaInCm = stainAreaInPixels * cmPerPixel^2
stainWidthInCm = stainWidthInPixels * cmPerPixel
% Overlay the bounding box.
hold on;
rectangle('Position', props.BoundingBox, 'EdgeColor', 'r', 'LineWidth', 2);
hold off;
%===============================================================================================
% Compute the cm per pixel calibration from this image.
function [tabletMask, cmPerPixel] = CalibrateSpatially(redChannel)
fontSize = 16;
%--------------------------------------------------------------------------------------------
% Display the red channel image.
subplot(2, 3, 2);
imshow(redChannel, [])
impixelinfo;
axis('on', 'image');
caption = sprintf('Red Channel Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
%--------------------------------------------------------------------------------------------
% FIND THE WHITE TABLET.
% Threshold the red channel.
% Interactively and visually set a threshold on a gray scale image using Image Analyst's utility.
% https://www.mathworks.com/matlabcentral/fileexchange/29372-thresholding-an-image?s_tid=srchtitle
%tabletMask = threshold(94, 255, r);
tabletMask = redChannel > 94;
% Fill holes and take the largest blob.
tabletMask = bwareafilt(imfill(tabletMask, 'holes'), 1);
% Show the mask image.
subplot(2, 3, 3);
imshow(tabletMask)
impixelinfo;
axis('on', 'image');
caption = sprintf('Final Tablet Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
%--------------------------------------------------------------------------------------------
% FIND THE AVERAGE WIDTH OF THE TABLET IN PIXELS. IT'S KNOWN TO BE 4.2 CM WIDE.
horizontalProfile = mean(tabletMask, 1);
% Display the pseudo-colored image.
subplot(2, 3, 4);
plot(horizontalProfile, 'b-', 'Linewidth', 2);
grid on;
caption = sprintf('Intensity Profile going across tablet');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Find the average width by thresholding at 0.5
insideTabletColumns = find(horizontalProfile > 0.5);
% Find left column
leftColumn = insideTabletColumns(1)
% Find the right column.
rightColumn = insideTabletColumns(end)
% Find the center-to-center distance in pixels
widthInPixels = rightColumn - leftColumn
% Put vertical red lines on those columns in the upper left image.
subplot(2, 3, 1);
hold on;
xline(leftColumn, 'Color', 'r', 'Linewidth', 2);
xline(rightColumn, 'Color', 'r', 'Linewidth', 2);
%--------------------------------------------------------------------------------------------
% COMPUTE THE SPATIAL CALIBRATION FACTOR IN UNITS OF CM/PIXEL
cmPerPixel = 4.2 / widthInPixels;
message = sprintf('The spatial calibration is %f cm per pixel (4.2 cm divided by %d pixels).', cmPerPixel, widthInPixels);
fprintf('%s\n.', message);
uiwait(helpdlg(message));
end % of function CalibrateSpatially()

Sign in to comment.


Umar
Umar on 7 Jan 2025

Hi @Tejaswi,

To successfully convert pixels to centimeters, you need to establish a clear relationship between the two units. This typically involves knowing how many pixels correspond to a specific physical measurement (in cm) within the context of your image. Here’s a structured approach to solve this issue:

1. Define Known Distances: Before you can convert pixels to centimeters, you need to set a reference distance. For example, if you know that a certain object in your image measures 10 cm and spans 200 pixels in the image, you can calculate the conversion factor.

2. Correcting Your Code: The error you're encountering arises because distanceInCm and distanceInPixels have not been defined in your code. Here’s how you might modify your code:

   % Define known distances
   distanceInCm = 10; % Example: known distance in cm
   distanceInPixels = 200; % Example: known distance in pixels
   % Calculate conversion factor
   cmPerPixel = distanceInCm / distanceInPixels;
   % Now to convert a length in pixels
   lengthInPixels = lengthOfDarkerRed; % Use the length measured from your    
   mask
   lengthInCm = lengthInPixels * cmPerPixel;
   % To convert an area in pixels to square cm:
   areaInPixels = ...; % Define or calculate this based on your analysis
   areaInSquareCm = areaInPixels * cmPerPixel^2;
   disp(['Length in cm: ', num2str(lengthInCm)]);

3. Example Usage: Let’s say you measure a component that is 150 pixels long and you have established that 200 pixels correspond to 10 cm (as per your calibration):

   distanceInCm = 10; 
   distanceInPixels = 200; 
   cmPerPixel = distanceInCm / distanceInPixels; % Results in 0.05 cm/pixel
   lengthOfDarkerRed = 150; % Example length measured from your component
   lengthInCm = lengthOfDarkerRed * cmPerPixel; 
   disp(['Length in cm: ', num2str(lengthInCm)]); 
   % This will output the converted length.

Here are some additional insights that I would like to share.

Calibration: It’s crucial to have accurate calibration measurements for reliable conversions from pixels to centimeters. If you're analyzing images of objects with known dimensions, use these as references.

Image Resolution: Remember that the conversion factor will vary based on the resolution of the image and how it was captured (e.g., camera settings). Always ensure consistency in how images are taken.

Error Handling: In production code, consider adding error handling for cases where either distanceInCm or distanceInPixels might not be defined or if they are zero.

By following these steps and using proper calibration, you should be able to convert pixel measurements into centimeters effectively without running into errors.

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!