There is some problem with insertshape function in my matlab program (2024)

11 views (last 30 days)

Show older comments

Shubham Sharma on 25 Jul 2024 at 10:49

  • Link

    Direct link to this question

    https://www.mathworks.com/matlabcentral/answers/2140111-there-is-some-problem-with-insertshape-function-in-my-matlab-program

  • Link

    Direct link to this question

    https://www.mathworks.com/matlabcentral/answers/2140111-there-is-some-problem-with-insertshape-function-in-my-matlab-program

Edited: Walter Roberson on 25 Jul 2024 at 16:37

Open in MATLAB Online

% Define area threshold (e.g., 100 pixels)

areaThreshold = 500; % Set your desired threshold value here

% Read the TIFF image

image = imread('quartz1.tif');

% Convert to grayscale if not already

if size(image, 3) == 3

grayImage = rgb2gray(image);

else

grayImage = image;

end

% Apply Gaussian blur

blurredImage = imgaussfilt(grayImage, 2);

% Enhance contrast

enhancedImage = imadjust(blurredImage);

% Apply sharpening

sharpenedImage = imsharpen(enhancedImage);

% Detect edges

edges = edge(sharpenedImage, 'Canny');

% Find contours

contours = bwconncomp(edges);

% Calculate properties for each grain

stats = regionprops(contours, 'Area', 'Perimeter', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'BoundingBox', 'PixelIdxList', 'Centroid');

% Process each grain

for i = 1:length(stats)

if stats(i).Area > areaThreshold

% Get the bounding box for each grain

bb = stats(i).BoundingBox;

grainRegion = imcrop(grayImage, bb);

% Create a new image to draw axes

% Get the ellipse properties

orientation = stats(i).Orientation;

majorAxisLength = stats(i).MajorAxisLength;

minorAxisLength = stats(i).MinorAxisLength;

perimeter = stats(i).Perimeter; % Perimeter value

centerX = stats(i).Centroid(1) - bb(1);

centerY = stats(i).Centroid(2) - bb(2);

% Compute the endpoints of the major and minor axes

majorAxisEnd1 = [centerX + majorAxisLength / 2 * cosd(orientation), centerY - majorAxisLength / 2 * sind(orientation)];

majorAxisEnd2 = [centerX - majorAxisLength / 2 * cosd(orientation), centerY + majorAxisLength / 2 * sind(orientation)];

minorAxisEnd1 = [centerX + minorAxisLength / 2 * cosd(orientation + 90), centerY - minorAxisLength / 2 * sind(orientation + 90)];

minorAxisEnd2 = [centerX - minorAxisLength / 2 * cosd(orientation + 90), centerY + minorAxisLength / 2 * sind(orientation + 90)];

% Ensure endpoints are within bounds of the image

majorAxisEnd1 = max(min(majorAxisEnd1, size(grainRegion, 2) - 1), 1);

majorAxisEnd2 = max(min(majorAxisEnd2, size(grainRegion, 2) - 1), 1);

minorAxisEnd1 = max(min(minorAxisEnd1, size(grainRegion, 2) - 1), 1);

minorAxisEnd2 = max(min(minorAxisEnd2, size(grainRegion, 2) - 1), 1);

% Draw the axes

grainImageWithAxes = insertShape(grainImageWithAxes, 'Line', [majorAxisEnd1, majorAxisEnd2], 'Color', 'red', 'LineWidth', 3);

grainImageWithAxes = insertShape(grainImageWithAxes, 'Line', [minorAxisEnd1, minorAxisEnd2], 'Color', 'blue', 'LineWidth', 3);

% Draw contour (perimeter)

contour = bwboundaries(contours.PixelIdxList{i});

contourVertices = contour{1} - [bb(1), bb(2)];

% Convert contourVertices to a cell array with one matrix

contourVerticesCell = {contourVertices};

% Draw the contour

grainImageWithAxes = insertShape(grainImageWithAxes, 'Polygon', 'Vertices', {contourVertices}, 'Color', 'green', 'LineWidth', 2);

% Add text annotations with larger font size

grainImageWithAxes = insertText(grainImageWithAxes, [10 10], sprintf('Major Axis: %.2f', majorAxisLength), 'FontSize', 12, 'TextColor', 'red', 'BoxColor', 'black');

grainImageWithAxes = insertText(grainImageWithAxes, [10 30], sprintf('Minor Axis: %.2f', minorAxisLength), 'FontSize', 12, 'TextColor', 'blue', 'BoxColor', 'black');

grainImageWithAxes = insertText(grainImageWithAxes, [10 50], sprintf('Perimeter: %.2f', perimeter), 'FontSize', 12, 'TextColor', 'green', 'BoxColor', 'black');

% Save the image with axes using PNG format

filename = sprintf('grain_%d_axes.png', i);

imwrite(grainImageWithAxes, filename, 'PNG');

% Display the image with axes

figure;

imshow(grainImageWithAxes);

title(sprintf('Sand Grain %d', i));

end

end

the error i am getting is

Error using insertShape

Expected POSITION to be one of these types:

cell

Error in insertShape>checkPosition (line 332)

validateattributes(position,{'cell'}, {'nonempty', 'vector'}, ...

Error in insertShape>validateAndParseInputs (line 256)

checkPosition(position, shape1);

Error in insertShape (line 129)

validateAndParseInputs(I, shape, position, varargin{:});

Error in untitled8 (line 74)

grainImageWithAxes = insertShape(grainImageWithAxes, 'Polygon', 'Vertices', {contourVertices}, 'Color', 'green', 'LineWidth', 2);

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

Answers (1)

Karan Singh on 25 Jul 2024 at 11:08

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2140111-there-is-some-problem-with-insertshape-function-in-my-matlab-program#answer_1490521

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2140111-there-is-some-problem-with-insertshape-function-in-my-matlab-program#answer_1490521

Open in MATLAB Online

  • tiffbucket.zip

@Shubham Sharma

It looks like there's an issue with the way the vertices are being passed to the insertShape function. The Vertices parameter expects a cell array. The conversion to a cell array is not being done correctly.

Here Is the corrected code.

% Define area threshold (e.g., 100 pixels)

areaThreshold = 500; % Set your desired threshold value here

% Read the TIFF image

unzip tiffbucket.zip

image = imread('indexedblobs.tiff');

% Convert to grayscale if not already

if size(image, 3) == 3

grayImage = rgb2gray(image);

else

grayImage = image;

end

% Apply Gaussian blur

blurredImage = imgaussfilt(grayImage, 2);

% Enhance contrast

enhancedImage = imadjust(blurredImage);

% Apply sharpening

sharpenedImage = imsharpen(enhancedImage);

% Detect edges

edges = edge(sharpenedImage, 'Canny');

% Find contours

contours = bwconncomp(edges);

% Calculate properties for each grain

stats = regionprops(contours, 'Area', 'Perimeter', 'MajorAxisLength', 'MinorAxisLength', 'Orientation', 'BoundingBox', 'PixelIdxList', 'Centroid');

% Process each grain

for i = 1:length(stats)

if stats(i).Area > areaThreshold

% Get the bounding box for each grain

bb = stats(i).BoundingBox;

grainRegion = imcrop(grayImage, bb);

% Create a new image to draw axes

grainImageWithAxes = cat(3, grainRegion, grainRegion, grainRegion);

% Get the ellipse properties

orientation = stats(i).Orientation;

majorAxisLength = stats(i).MajorAxisLength;

minorAxisLength = stats(i).MinorAxisLength;

perimeter = stats(i).Perimeter; % Perimeter value

centerX = stats(i).Centroid(1) - bb(1);

centerY = stats(i).Centroid(2) - bb(2);

% Compute the endpoints of the major and minor axes

majorAxisEnd1 = [centerX + majorAxisLength / 2 * cosd(orientation), centerY - majorAxisLength / 2 * sind(orientation)];

majorAxisEnd2 = [centerX - majorAxisLength / 2 * cosd(orientation), centerY + majorAxisLength / 2 * sind(orientation)];

minorAxisEnd1 = [centerX + minorAxisLength / 2 * cosd(orientation + 90), centerY - minorAxisLength / 2 * sind(orientation + 90)];

minorAxisEnd2 = [centerX - minorAxisLength / 2 * cosd(orientation + 90), centerY + minorAxisLength / 2 * sind(orientation + 90)];

% Ensure endpoints are within bounds of the image

majorAxisEnd1 = max(min(majorAxisEnd1, size(grainRegion, 2) - 1), 1);

majorAxisEnd2 = max(min(majorAxisEnd2, size(grainRegion, 2) - 1), 1);

minorAxisEnd1 = max(min(minorAxisEnd1, size(grainRegion, 2) - 1), 1);

minorAxisEnd2 = max(min(minorAxisEnd2, size(grainRegion, 2) - 1), 1);

% Draw the axes

grainImageWithAxes = insertShape(grainImageWithAxes, 'Line', [majorAxisEnd1, majorAxisEnd2], 'Color', 'red', 'LineWidth', 3);

grainImageWithAxes = insertShape(grainImageWithAxes, 'Line', [minorAxisEnd1, minorAxisEnd2], 'Color', 'blue', 'LineWidth', 3);

% Draw contour (perimeter)

contour = bwboundaries(contours.PixelIdxList{i});

contourVertices = contour{1} - [bb(1), bb(2)];

% Convert contourVertices to a cell array with one matrix

contourVerticesCell = {contourVertices};

% Draw the contour

grainImageWithAxes = insertShape(grainImageWithAxes, 'Polygon', contourVerticesCell, 'Color', 'green', 'LineWidth', 2);

% Add text annotations with larger font size

grainImageWithAxes = insertText(grainImageWithAxes, [10 10], sprintf('Major Axis: %.2f', majorAxisLength), 'FontSize', 12, 'TextColor', 'red', 'BoxColor', 'black');

grainImageWithAxes = insertText(grainImageWithAxes, [10 30], sprintf('Minor Axis: %.2f', minorAxisLength), 'FontSize', 12, 'TextColor', 'blue', 'BoxColor', 'black');

grainImageWithAxes = insertText(grainImageWithAxes, [10 50], sprintf('Perimeter: %.2f', perimeter), 'FontSize', 12, 'TextColor', 'green', 'BoxColor', 'black');

% Save the image with axes using PNG format

filename = sprintf('grain_%d_axes.png', i);

imwrite(grainImageWithAxes, filename, 'PNG');

% Display the image with axes

figure;

imshow(grainImageWithAxes);

title(sprintf('Sand Grain %d', i));

end

end

There is some problem with insertshape function in my matlab program (3)

There is some problem with insertshape function in my matlab program (4)

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

See Also

Categories

MATLABGraphics2-D and 3-D PlotsContour Plots

Find more on Contour Plots in Help Center and File Exchange

Tags

  • insertshape

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


There is some problem with insertshape function in my matlab program (5)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

There is some problem with insertshape function in my matlab program (2024)

FAQs

Why MATLAB is not working properly? ›

Try updating or reinstalling your graphics driver. Disable Third-Party Services and Startup Programs: A third-party service or program might be causing a conflict. You can perform a clean boot by disabling all non-Microsoft services and startup programs and then try to start MATLAB.

What is the insert function in MATLAB? ›

The insert function exports the data in its current MATLAB format. If data is a structure, then field names in the structure must match colnames . If data is a table or a dataset array, then the variable names in the table or dataset array must match colnames .

How do I fix errors in MATLAB? ›

If you are unfamiliar with the problem, right-click the highlighted code. The first item in the context menu shows the suggested fix. Select the item to apply the fix. If multiple instances of a problem exist, MATLAB might offer to apply the suggested fix for all instances of the problem.

How do I fix unrecognized variable or function in MATLAB? ›

Possible Solutions
  1. Verify Spelling of Function or Variable Name. ...
  2. Verify Inputs Correspond to the Function Syntax. ...
  3. Make Sure Function Name Matches File Name. ...
  4. Make Sure Necessary Toolbox Is Installed and Correct Version. ...
  5. Verify Path Used to Access Function Toolbox. ...
  6. Confirm The License Is Active.

Is MATLAB becoming obsolete? ›

MATLAB is almost dropping off from the top 20 for the first time in more than a decade. In April 2021, it was at the 19th position, and now, a year after that, it has dropped further. MATLAB finds its usage in the numerical analysis domain and is often combined with Simulink. Both come from MathWorks company.

What are the weaknesses of MATLAB? ›

  • Limitations.
  • Sample Time and Solver Restrictions.
  • Algebraic Loops.
  • Unsupported Simulink Tools and Features.
  • Restricted Simulink Tools.
  • Simulink Tools Not Compatible with Simscape Blocks.
  • Code Generation. Code Generation and Fixed-Step Solvers.

Where is the INSERT function? ›

Go to the Formulas ribbon – choose either the Insert Function icon to bring up the Insert Function dialog box (same dialog box you would get with the first method), or click the arrow next to the correct category in the Function Library Group, and then choose the desired function.

How to INSERT inset in MATLAB? ›

  1. Open a existing figure that is going to be the main figure. command: openfig('figure.fig') ...
  2. With the main figure opened write in the command window: handaxes2 = axes('position', [0.52 0.52 0.3 0.3]); ...
  3. Plot the second figure, the inset figure, with your data. Plot as you would normally:
Jun 21, 2019

How do you solve problems in MATLAB? ›

For example, solve(x + 1 == 2, x) solves the equation x + 1 = 2 for x. S = solve( eqn , var , Name,Value ) uses additional options specified by one or more Name,Value pair arguments. Y = solve( eqns , vars ) solves the system of equations eqns for the variables vars and returns a structure that contains the solutions.

What are the two kinds of errors in MATLAB? ›

There are two types of errors that appear in MATLAB expressions: syntax errors and runtime errors. Together, we generically refer to these errors as being bugs in the MATLAB code. The debugging process is the procedure of finding these bugs and fixing them.

What is the fix function in MATLAB? ›

Y = fix( X ) rounds each element of X to the nearest integer toward zero. This operation effectively truncates the numbers in X to integers by removing the decimal portion of each number: For positive numbers, the behavior of fix is the same as floor . For negative numbers, the behavior of fix is the same as ceil .

How do you find the error function in MATLAB? ›

erf( X ) represents the error function of X . If X is a vector or a matrix, erf(X) computes the error function of each element of X .

How to detect error in MATLAB program? ›

To generate CRC code bits and append them to input data, call the crcGenerate function specifying an input message and the CRC configuration object. To detect errors in input data using CRC code bits, call the crcDetect function specifying an codeword and the CRC configuration object.

How do you solve for an unknown variable in MATLAB? ›

To solve for a variable other than x , specify that variable instead. For example, solve eqn for b . If you do not specify a variable, solve uses symvar to select the variable to solve for. For example, solve(eqn) solves eqn for x .

Why is my MATLAB program not running? ›

Sometimes, another program or issue with the computer may be preventing MATLAB from starting. Restarting your computer may stop what is interfering with MATLAB launching correctly. One of the most common reasons MATLAB will fail to start is that something has corrupted the MATLAB preferences directory.

How can I improve my MATLAB? ›

You ARE interested in improving your skills AT MATLAB.
  1. Read the tutorials. They seem reasonable enough.
  2. Find a project that interests you, and try to solve small problems in that area. If there is no project that interests you, then why are you bothering to learn MATLAB? ...
  3. Learn to use vectors. ...
  4. START WRITING CODE!
Feb 13, 2015

How do I troubleshoot MATLAB? ›

Troubleshooting
  1. Server Startup Failures. Check the reasons resulting in the server not starting and ways to fix them.
  2. Server Logs. Check the log files associated with MATLAB Web App Server.
  3. Diagnostics. Check the status of each web app.
  4. Web App Session Log. Check the web app session log.

How do I make MATLAB run smoother? ›

Place independent operations outside loops — If code does not evaluate differently with each for or while loop iteration, move it outside of the loop to avoid redundant computations. Create new variables if data type changes — Create a new variable rather than assigning data of a different type to an existing variable.

Top Articles
Cato's Dozen Crossword
Resource Guides: Distinguish between types of publications: Popular Magazines
Tripadvisor Antigua Forum
Aged Grimm Character Nyt Crossword
Fresno Farm And Garden By Owner
Reports of romance scams hit record highs in 2021
24 Hour Car Wash Queens Ny
Jeff Liebler Wife
24 Hour Bookings Savannah
Sir Mo Farah says 'sport saved me' after finishing final race of illustrious career at Great North Run
8x20, 8x40 Shipping containers storage container for rent or sale - general for sale - by dealer - craigslist
Sunshine999
Fifi's Boyfriend Crossword Clue
What Is Flipping Straights Ted Lasso
Herman Kinn Funeral Home Obituaries
For My Derelict Favorite Novel Online
Busted Newspaper Williams County
Uhcs Patient Wallet
Sound Of Freedom Showtimes Near Sperry's Moviehouse Holland
Linktree Teentinyangel
1v1 lol unblocked Game- Play Unblocked Game Online for Free!
Aspen Portal Amherst Ny
Toothio Login
Taxi Driver Kdrama Dramacool
Apria Healthcare - 26 Reviews - Sacramento, CA
Samanthaschwartz Fapello
2Lookmovie
Frederik Zuiderveen Borgesius on LinkedIn: Amazingly quick work by Arnoud💻 Engelfriet! Can’t wait to dive in.
Soul of the Brine King PoE Pantheon 3.14 Upgrade
Www.publicsurplus.com Motor Pool
Amex Platinum Cardholders: Get Up to 10¢ Off Each Gallon of Gas via Walmart Plus Gas Discount
Walgreens Pharmacy On Jennings Station Road
Brublackvip
Family Leisure Sale
Heiwa Coin
Wbap Iheart
Lehigh Wheelmen Meetup
How Much Is 10000 Nickels
Stellaris Resolution
Phase 3 Cataclysm Classic New Changes, Preparation and Investments Guide
Dr Ayad Alsaadi
Goose Band Setlists
Hobby Lobby Locations Near Me
Ew41.Ultipro
Ap Bio Unit 2 Progress Check Mcq
Lavender Dreams Nails Walnut Creek Photos
Trapshooters.com Discussion Forum
Georgiatags.us/Mvdkiosk
Best Fishing Xp Osrs
H'aanit's Third Chapter | Gamer Guides: Your ultimate sou...
Gulfstream Park Entries And Results
O2 Fitness West Ashley Photos
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5587

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.