我正在撰寫一個函式來在 MATLAB 中分割影像。我想做一個簡單的分割,我首先對列中的元素求和,然后選擇大于閾值的像素位置,并僅顯示原始影像中的那些像素[![在此處輸入影像描述]影像。我在下面撰寫了一個函式,它可以對像素強度求和,我需要幫助來選擇強度大于閾值的像素位置并僅顯示影像的那部分。
function S = image_segment(im)
% im is the image to segment
nrofsegments = 5; % there is 5 fragments for this image
S = cell(1,nrofsegments);
m = size(im,1);
n = size(im,2);
for kk = 1:nrofsegments
S_sum=sum(im); %sum the intensity along column
S_position = ... % get pixel position where the pixel intensity is greater than 128
S{kk} = ... % im(S_position), only part of image with this pixel position
end
uj5u.com熱心網友回復:
此代碼應該適用于您的影像。請在線查找解釋。
% Read your test image from the web
im = imread('https://i.stack.imgur.com/qg5gx.jpg');
% Get sum of intensities along the columns
colSum = sum(im);
% Set a proper threshold (128 was not working for me)
thresh = 300;
% Get an 1-D logical array indicating which columns have letters
hasLetter = colSum > thresh;
% Get the difference of consecutive values in hasLetter
hasLetterDiff = diff( hasLetter ) ;
% If this is greater than 0, we have the start of a letter.
% The find gets the indices where this is true.
% Then, we add one to compensate for the offset introduced by diff.
letterStartPos = find( hasLetterDiff > 0 ) 1;
% Use a similar approach to find the letter end position
% Here, we search for differences smaller than 0.
letterEndPos = find( hasLetterDiff < 0 ) 1;
% Cut out image from start and end positions
numSegments = 5;
S = cell(1, numSegments );
for k = 1 : numel(S)
S{k} = im( :, letterStartPos(k) : letterEndPos(k));
end
您還應該考慮添加一些代碼,以使其在少于 5 個段的情況下具有故障安全性。此外,我建議對colSum
.
替代方案:除了推導開始和停止位置,還可以直接使用splitapply
(在 R2015 中引入)hasLetterDiff
,如下所示:
S = splitapply( @(X) { im(:,X) }, 1 : numel( hasLetter), [1 cumsum( abs( hasLetterDiff))] 1);
S = S(2:2:end);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/507947.html
上一篇:系統地從單元格中洗掉字串