# How can I detect a triangle in my image?

67 views (last 30 days)

Show older comments

Please I need help for detect triangles in the image I attached. I don't know how to do it.

##### 0 Comments

### Answers (3)

Abolfazl Chaman Motlagh
on 14 Dec 2021

Edited: Abolfazl Chaman Motlagh
on 15 Dec 2021

Hi. in case your problem is exactly what you attached. here is an easy solution i can provide:

I = imread('image.jpeg'); %read image

I = rgb2gray(I); % transform image to grayscale

C = corner(I); % find corners in image

G = imgradient(I); % create gradient of image

BW = G>max(G(:))*0.1; % make a binary image by thresholding gradient image

CC = bwconncomp(BW); % extract connected components in binary image

ind = sub2ind(size(I),C(:,2),C(:,1)); % transform coordinate of corner points to linear index

for component=1:CC.NumObjects

% determine which corners belong to which components

Index_in_componet{component} = ismember(ind,CC.PixelIdxList{component});

% check if number of corner belong to a components is equal 3

Is_triangle(component) = sum(Index_in_componet{component}) == 3;

end

triangle = find(Is_triangle); % find the component with 3 corner

% find XY cordinate of Corners in Triangle

[Triangle_points_Y,Triangle_points_X] = ind2sub(size(I),ind(Index_in_componet{triangle}));

% find XY cordinate of All points in selected component

[Row,Col] = ind2sub(size(I),CC.PixelIdxList{triangle});

% Visualization

J = zeros(size(I));

for i=1:numel(Row)

J(Row(i),Col(i))=1;

end

figure;

subplot(1,2,1);

imshow(I)

hold;

scatter(Triangle_points_X,Triangle_points_Y,50,'b','filled')

subplot(1,2,2);

imshow(J);

The Output :

##### 3 Comments

yanqi liu
on 15 Dec 2021

yes，sir，may be use the Circularity，such as

clc; clear all; close all;

img = imread('https://www.mathworks.com/matlabcentral/answers/uploaded_files/834120/image.jpeg');

bw = ~im2bw(img);

stats = regionprops(bw, 'BoundingBox', 'Circularity');

cis = cat(1, stats.Circularity);

id = cis<1 & cis>0.5;

figure; imshow(img, []);

hold on; rectangle('position', stats(id).BoundingBox, 'EdgeColor', 'r', 'LineWidth', 2)

##### 5 Comments

Image Analyst
on 15 Dec 2021

Edited: Image Analyst
on 15 Dec 2021

Lots of ways to do it. Here is one:

rgbImage = imread('image.jpeg');

[rows, columns, numberOfColorChannels] = size(rgbImage)

subplot(2, 2, 1);

imshow(rgbImage);

impixelinfo

mask = rgb2gray(rgbImage) < 128;

subplot(2, 2, 2);

imshow(mask);

impixelinfo

[labeledImage, numRegions] = bwlabel(mask);

props = regionprops(mask, 'Area')

allAreas = [props.Area]

index = find(allAreas == 2635)

triangle = ismember(labeledImage, index);

subplot(2, 2, 3);

imshow(triangle);

##### 2 Comments

Image Analyst
on 16 Dec 2021

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!