此代碼對我的作品,假設你的黑色邊框像素全部爲零。如果圖像的黑色邊框中存在非零像素(可能是由於量化和壓縮僞像 - 畢竟...您的圖像爲JPEG),那麼此代碼將不起作用。這段代碼正在做的是首先檢查所有列,看看是否有任何非零像素。然後它通過確定第一個非零列並轉到最後一個非零列來計算出哪裏需要裁剪。此代碼還假定非零列爲對稱,這就是爲什麼您在zeros
聲明中除以2的原因。順便說一句,zeros
是MATLAB中的一個內置函數。我不建議你創建一個具有這個名字的變量,因爲你的後面的代碼可能需要這個函數,而且你無意中在這個函數上映射了一個變量。
不過,這是我做的測試,看看你的代碼是否工作。我使用了MATLAB的系統路徑cameraman.tif
的內置圖像,並在圖像周圍創建了一個10像素邊框。然後,我跑到你的代碼,看看有什麼我會得到:
im = imread('cameraman.tif');
I1 = padarray(im2double(im), [10 10]);
運行你的代碼,這是數字我得到:
![enter image description here](https://i.stack.imgur.com/jlSk1.png)
有運行的代碼時存在一定的前提條件因此在使用前請記住這一點:
- 此處假設爲entir圍繞圖像的黑色邊框。
- 這假設所有的黑色邊框像素都是零。
- 如果您的邊框具有非零像素,即使它可能可視看起來像有非零像素,那麼此代碼將不起作用。
因此,我建議您在進行之前確定邊界爲零,以確保邊界爲零。然後,您將使用此圖像計算您有多少個邊界像素。因此,做這樣的事情。
I1=im2double(imread('dart.jpg')); %// Read in the image
I1thresh = I1 >= (10/255); %// As an example - Note the division by 255 as you did im2double
sizeI = size(I1);
zeros = floor((sizeI(2) - min(sum(any(I1thresh))))/2); %// Note the change in any
I2 = I1(:, zeros : sizeI(2)-zeros, :);
I2thresh = I1thresh(:, zeros : sizeI(2)-zeros, :); % // Note new variable
nonZero = sum(any(I1thresh,2)); %// Note the change in any
sizeI2 = size(I2);
zerosRows = floor((sizeI(1) - min(sum(any(I2thresh, 2))))/2); %// Note change in any
I3 = I2(zerosRows : sizeI2(1)-zerosRows, :, :);
subplot(1,3,1), imshow(I1);title('Figure 1');
subplot(1,3,2), imshow(I2);title('Figure 2');
subplot(1,3,3), imshow(I3);title('Figure 3');
編輯 - 非均勻的黑色邊框
從你的意見,你說你的黑色邊框可能不是對稱的。在這種情況下,您需要具有邏輯來確定黑邊與黑邊的結束位置的起始位置。您將其應用於黑色邊框的行和列。在這種情況下,我會使用find
命令,並沿着行和列使用any
操作,並確定行和列非零的最小和最大索引。這完全對應於MATLAB中關於代碼的最小和最大操作。我將使用帶閾值的修改算法來規避任何量化或壓縮僞像。因此:
I1=im2double(imread('dart.jpg')); %// Read in the image
I1thresh = I1 >= (10/255); %// As an example - Note the division by 255 as you did im2double
%// Removed as this is no longer needed
%// sizeI = size(I1);
nonZeroCols = find(any(I1thresh)); %// Change
minCol = min(nonZeroCols); %// Change
maxCol = max(nonZeroCols); %// Change
I2 = I1(:, minCol : maxCol, :);
I2thresh = I1thresh(:, minCol : maxCol, :); % // Note new variable
%// Commented out. Don't see this being used anywhere
%//nonZero = sum(any(I1thresh,2)); %// Note the change in any
%// Removed as this is no longer needed
%//sizeI2 = size(I2);
nonZeroRows = find(any(I2thresh, 2)); %// Change
minRow = min(nonZeroRows); %// Change
maxRow = max(nonZeroRows); %// Change
I3 = I2(minRow : maxRow, :, :); %// Change
subplot(1,3,1), imshow(I1);title('Figure 1');
subplot(1,3,2), imshow(I2);title('Figure 2');
subplot(1,3,3), imshow(I3);title('Figure 3');
上面的代碼現在應該適用於任何大小的黑色邊框。
親愛的朋友:)我知道這是什麼代碼做.. 我認爲這個問題是在beacouse我的照片的黑色邊框不對稱的 我怎樣才能改變這種狀況 – 2014-08-31 09:12:59
@SEBASTIANLOTuS - 完成。檢查我的編輯。歡呼 – rayryeng 2014-08-31 18:26:52
@SEBASTIANLOTuS - 你需要更多的幫助嗎? – rayryeng 2014-09-03 07:39:11