Как вырезать обнаруженный объект (круг) из изображения и сохранить его? - PullRequest
2 голосов
/ 24 мая 2019

Приведенный ниже код классифицирует объекты на основе их округлости, используя bwboundaries.

. Он оценивает площадь и периметр каждого объекта и использует эти результаты для формирования простой метрики, указывающей округлость объекта со следующей метрикой:

metric = 4*pi*area/perimeter^2

Этот показатель равен 1 только для круга и меньше единицы для любой другой фигуры.Но в этом коде я использую пороговое значение 0,80, чтобы только объекты со значением метрики, превышающим 0,80, были классифицированы как круглые.

Мой вопрос: когда данный объект классифицируется как круглый, как можноЯ обрезаю его из исходного изображения img (не I или bw) и сохраняю как новое изображение?

Я думаю, что для этого будет достаточно использовать матрицу меток и матрицу границ., но до сих пор не знаю, как ими манипулировать.

img=imread('cap.png');
I = rgb2gray(img);

% Step 2: Threshold the Image
bw1 = imbinarize(I);
bw = imcomplement(bw1);

% Step 3: Remove the Noise
bw = bwareaopen(bw,30);      % remove small objects
bw = imfill(bw,'holes');    


% Step 4: Find the Boundaries
[B,L] = bwboundaries(bw,'noholes');
imshow(label2rgb(L,@jet,[.5 .5 .5]))
hold on
for k = 1:length(B)
  boundary = B{k};
  plot(boundary(:,2),boundary(:,1),'w','LineWidth',2)
end



% Step 5: Determine which Objects are Round
stats = regionprops(L,'Area','Centroid');
threshold = 0.80;
% loop over the boundaries
for k = 1:length(B)

  % obtain (X,Y) boundary coordinates corresponding to label 'k'
  boundary = B{k};

  % compute a simple estimate of the object's perimeter
  delta_sq = diff(boundary).^2;    
  perimeter = sum(sqrt(sum(delta_sq,2)));

  % obtain the area calculation corresponding to label 'k'
  area = stats(k).Area;

  % compute the roundness metric
  metric = 4*pi*area/perimeter^2;

  % display the results
  metric_string = sprintf('%2.2f',metric);

  % Test if the current object classified as a round
  if metric > threshold
    % HERE, I want to crop the current object from the 'img' 
    % and save it as a new image 
  end

end

title(['Metrics closer to 1 indicate that ',...
       'the object is approximately round'])

1 Ответ

2 голосов
/ 24 мая 2019

Вы можете дополнительно добавить атрибут BoundingBox к regionprops, который фактически даст вам пределы того, где капля распространяется внутри ограничительной рамки, и вы можете использовать их, чтобы обрезать ваше изображение и сохранить его.Он будет иметь вид [x y width height], где x и y - верхние левые координаты ограничительной рамки, а width и height - ширина и высота.x будет координатой столбца, а y будет координатой строки.Вы можете использовать imcrop, чтобы окончательно обрезать изображение.

img=imread('cap.png');
I = rgb2gray(img);

% Step 2: Threshold the Image
bw1 = imbinarize(I);
bw = imcomplement(bw1);

% Step 3: Remove the Noise
bw = bwareaopen(bw,30);      % remove small objects
bw = imfill(bw,'holes');    


% Step 4: Find the Boundaries
[B,L] = bwboundaries(bw,'noholes');
imshow(label2rgb(L,@jet,[.5 .5 .5]))
hold on
for k = 1:length(B)
  boundary = B{k};
  plot(boundary(:,2),boundary(:,1),'w','LineWidth',2)
end



% Step 5: Determine which Objects are Round
stats = regionprops(L,'Area','Centroid','BoundingBox'); % Change
threshold = 0.80;
% loop over the boundaries
for k = 1:length(B)

  % obtain (X,Y) boundary coordinates corresponding to label 'k'
  boundary = B{k};

  % compute a simple estimate of the object's perimeter
  delta_sq = diff(boundary).^2;    
  perimeter = sum(sqrt(sum(delta_sq,2)));

  % obtain the area calculation corresponding to label 'k'
  area = stats(k).Area;

  % compute the roundness metric
  metric = 4*pi*area/perimeter^2;

  % display the results
  metric_string = sprintf('%2.2f',metric);

  % Test if the current object classified as a round
  if metric > threshold
    % HERE, I want to crop the current object from the 'img' 
    % and save it as a new image 

    % New - crop image
    bb = stats(k).BoundingBox;
    img_crop = imcrop(img, bb);

    % New - Save the image
    imwrite(img_crop, sprintf('crop%d.png', k));
  end

end

title(['Metrics closer to 1 indicate that ',...
       'the object is approximately round'])

Обратите внимание, что я использую imwrite, чтобы сохранить обрезку в файл, и она называетсяв зависимости от того, какой блоб-идентификатор вы смотрите.Поэтому, если есть несколько больших или круглых объектов, которые удовлетворяют критериям, вы сохраните их все.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...