How to crop a circle from an image?
17 次查看(过去 30 天)
显示 更早的评论
hey, asking for the second time.
I need to find a circle in an image and crop that region of the circle to a new image, I already found a way to find the circle using "imfindcircle" fuction, but when I use that function it only marks the circle and i need to crop it somehow but I dont know what info i can use... thanks in advance
2 个评论
Ameer Hamza
2020-3-11
Can you post the image and code you have developed until now? It will be easier for us to suggest a solution if we know what you have already done.
采纳的回答
Turlough Hughes
2020-3-11
Try the following tutorial:
% Setup
clear
close all
clc
inputImg = imread('cameraman.tif');
% Show demo Image
hf = figure();
set(hf,'Units', 'Normalized', 'OuterPosition', [0 0 1 1])
subplot(1,2,1)
imshow(inputImg)
% Example of data output from findcircles with two circle outputs
centers = [50 50; 150 200];
radii = [20; 30];
% Draw circles on image (just for demo)
drawcircle('Center',centers(1,:),'Radius',radii(1))
drawcircle('Center',centers(2,:),'Radius',radii(2))
% Generate binary image (mask) for representing cropped regions
mask = false(size(inputImg));
for c = 1:numel(radii)
[colsInImg,rowsInImg] = meshgrid(1:size(inputImg,1),1:size(inputImg,2));
circlePixels = (rowsInImg - centers(c,2)).^2 ...
+ (colsInImg - centers(c,1)).^2 <= radii(c).^2;
mask(circlePixels) = true;
end
% Use mask to get cropped image
cropped = inputImg;
cropped(~mask) = false;
% Show results
subplot(1,2,2)
imshow(cropped)
2 个评论
Turlough Hughes
2020-3-12
Using your code to find the region of interest that you wish to crop:
clear
close all
clc
A = imread('Speed.jpg');
% Resize the image
rowSZ = size(A, 1);
colSZ = size(A, 2);
rows = 250*(colSZ/rowSZ);
J = imresize(A, [rows 250]);
% Show image
imshow(J)
% Set circle radius to find
Rmin = 50;
Rmax = 100;
% Find circles within the raidus
[centers, radii, metric] = imfindcircles(J,[Rmin Rmax]);
% Show circle on the image
viscircles(centers, radii,'EdgeColor','b');
You could then do the following to crop the region inside the circle. Note that I reduced the radius by 2 pixels because otherwise some of the red gets included, and that I set the background colour to white.
[colsInImg,rowsInImg] = meshgrid(1:size(J,1),1:size(J,2));
circlePixels = (colsInImg - centers(1,1)).^2 + ...
(rowsInImg - centers(1,2)).^2 < (radii(1)-2).^2;
Jcrop = J;
Jcrop(repmat(~circlePixels,1,1,3)) = 255;
imshow(Jcrop)
figure(), imshow(Jcrop)
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!