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

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 commentaires

Unrecognized function or variable 'distanceInCm'.
Error in main (line 40)
cmPerPixel = distanceInCm / distanceInPixels;
can you please share the full code here?
Thank you
% Load the image
image = imread('frame_0505.jpg'); % Replace with your image file
imshow(image);
title('Original Image');
% Define thresholds for darker red
redMin = [100, 0, 0]; % Minimum RGB values for darker red
redMax = [150, 50, 50]; % Maximum RGB values for darker red
% Create a mask for darker red
darkerRedMask = (image(:,:,1) >= redMin(1) & image(:,:,1) <= redMax(1)) & ...
(image(:,:,2) >= redMin(2) & image(:,:,2) <= redMax(2)) & ...
(image(:,:,3) >= redMin(3) & image(:,:,3) <= redMax(3));
% Display the mask
figure;
imshow(darkerRedMask);
title('Darker Red Mask');
% Remove noise by eliminating small objects
darkerRedMask = bwareaopen(darkerRedMask, 50); % Adjust size threshold if necessary
% Find connected components
cc = bwconncomp(darkerRedMask);
stats = regionprops(cc, 'PixelIdxList', 'MajorAxisLength');
% Find the longest darker red component
[~, idx] = max([stats.MajorAxisLength]);
longestDarkerRedComponent = false(size(darkerRedMask));
longestDarkerRedComponent(cc.PixelIdxList{idx}) = true;
% Display the longest darker red component
figure;
imshow(longestDarkerRedComponent);
title('Longest Darker Red Component');
% Measure the length of the longest darker red component
lengthOfDarkerRed = stats(idx).MajorAxisLength;
disp(['The length of the darker red region is: ', num2str(lengthOfDarkerRed), 'pixels']);
This is the code from which im getting values in pixels.
Your code does not define variables distanceInCm or distanceInPixels. I can create the same error here:
cmPerPixel = distanceInCm / distanceInPixels;
Unrecognized function or variable 'distanceInCm'.
@Tejaswi , can you share the correct code which contains "cmPerPixel = distanceInCm / distanceInPixels"?
Thank you
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)

Connectez-vous pour commenter.

Réponses (2)

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 commentaires

Tejaswi
Tejaswi le 7 Jan 2025
Modifié(e) : Tejaswi le 7 Jan 2025
so i have a set of images in which i want to measure the length of darker region,that to in cm,one of the demo of those images Im attatching along with it, in this a rectangular strip is there,whose length is 4.2cm,my aim is to measure darker red reagion.i need a code for it,which can give me measured length of all the images from a file in the form of excel sheet.Also please refer the complete code that i have dropped in first comment of the question

Hi @Tejaswi,

To achieve the desired outcome of measuring the length of darker regions in images and exporting the results to an Excel sheet, we can follow a systematic approach using MATLAB. Below, I will outline the steps involved and provide a complete code example.

1. Image Preprocessing: Load the images and convert them to grayscale to simplify the analysis. 2. Thresholding: Apply a threshold to isolate the darker red regions from the rest of the image. 3. Measurement Calibration: Use the known length of the rectangular strip (4.2 cm) to calibrate pixel measurements to centimeters. 4. Length Measurement: Calculate the length of the darker regions in pixels and convert it to centimeters. 5. Exporting Results: Save the measured lengths into an Excel file.

Here is a complete MATLAB code that implements the above steps:

% Define the folder containing the images
imageFolder = 'path_to_your_image_folder';
imageFiles = dir(fullfile(imageFolder, '*.jpg')); 
% Adjust the file type as needed
numImages = length(imageFiles);
% Initialize an array to store lengths
lengthsInCm = zeros(numImages, 1);
% Calibration factor (pixels per cm)
calibrationLengthInCm = 4.2; % Known length in cm
calibrationPixels = 100; 
% Replace with the actual pixel length of the   strip in the image
calibrationFactor = calibrationLengthInCm / calibrationPixels;
% Loop through each image
for i = 1:numImages
  % Read the image
  img = imread(fullfile(imageFolder, imageFiles(i).name));
    % Convert to grayscale
    grayImg = rgb2gray(img);
    % Apply a threshold to isolate darker regions
    % Adjust the threshold value as necessary
    thresholdValue = 100; % Example threshold
    binaryImg = grayImg < thresholdValue;
    % Find the boundaries of the darker regions
    boundaries = bwboundaries(binaryImg, 'noholes');
    % Measure the length of the largest region
    maxLength = 0;
    for j = 1:length(boundaries)
        boundary = boundaries{j};
        % Calculate the length of the boundary
        lengthInPixels = sum(sqrt(diff(boundary(:,1)).^2 +                 diff(boundary(:,2)).^2));
        lengthInCm = lengthInPixels * calibrationFactor; % Convert to cm
        % Update maxLength if this is the longest found
        if lengthInCm > maxLength
            maxLength = lengthInCm;
        end
    end
    % Store the measured length
    lengthsInCm(i) = maxLength;
  end
% Create a table for the results
resultsTable = table({imageFiles.name}', lengthsInCm, 'VariableNames',
{'ImageName', 'Length_cm'});
% Write the results to an Excel file
writetable(resultsTable, 'MeasuredLengths.xlsx');
disp('Length measurements have been saved to MeasuredLengths.xlsx');

Explanation of code

Image Loading: The code begins by specifying the folder containing the images and loading all JPEG files.

Calibration: The calibration factor is calculated based on the known length of the rectangular strip in centimeters and its corresponding pixel length in the image.

Image Processing: Each image is converted to grayscale, and a binary mask is created to isolate the darker regions using a threshold.

Boundary Detection: The bwboundaries function is used to find the boundaries of the darker regions, and the length of these boundaries is calculated.

Length Calculation: The length in pixels is converted to centimeters using the calibration factor.

Results Export: Finally, the results are compiled into a table and exported to an Excel file named MeasuredLengths.xlsx.

This MATLAB code provides a comprehensive solution for measuring the lengths of darker regions in a set of images and exporting the results to an Excel sheet. Adjust the threshold and calibration values as necessary to suit your specific images and requirements. If you have any further questions or need additional modifications, feel free to ask!

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
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()

Connectez-vous pour commenter.

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.

Produits

Version

R2024b

Question posée :

le 6 Jan 2025

Commenté :

le 10 Jan 2025

Community Treasure Hunt

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

Start Hunting!

Translated by