4

I want to load an RGB image in MATLAB and turn it into a binary image, where I can choose how many pixels the binary image has. For instance, I'd load a 300x300 png/jpg image into MATLAB and I'll end up with a binary image (pixels can only be #000 or #FFF) that could be 10x10 pixels.

This is what I've tried so far:

load trees % from MATLAB
gray=rgb2gray(map); % 'map' is loaded from 'trees'. Convert to grayscale.
threshold=128;
lbw=double(gray>threshold);
BW=im2bw(X,lbw); % 'X' is loaded from 'trees'.
imshow(X,map), figure, imshow(BW)

(I got some of the above from an internet search.)

I just end up with a black image when doing the imshow(BW).

4

2 に答える 2

8

最初の問題は、インデックス付きイメージ( colormap を持つmap) とRGB イメージ(持たない) を混同していることです。trees.mat例で読み込むサンプルの組み込みイメージはインデックス付きイメージであるため、関数を使用して最初にグレースケール強度イメージind2grayに変換する必要があります。RGB 画像の場合、関数は同じことを行います。rgb2gray

次に、グレースケール イメージをバイナリ イメージに変換するために使用するしきい値を決定する必要があります。graythreshプラグインするしきい値を計算する関数im2bw(または新しい) をお勧めしますimbinarize。あなたの例であなたがしていることを達成する方法は次のとおりです。

load trees;             % Load the image data
I = ind2gray(X, map);   % Convert indexed to grayscale
level = graythresh(I);  % Compute an appropriate threshold
BW = im2bw(I, level);   % Convert grayscale to binary

元の画像と結果BWは次のようになります。

ここに画像の説明を入力

ここに画像の説明を入力

RGB 画像入力の場合は、上記のコードind2grayをに置き換えるだけです。rgb2gray

画像のサイズ変更に関しては、次のimresizeように Image Processing Toolbox 関数を使用して簡単に行うことができます。

smallBW = imresize(BW, [10 10]);  % Resize the image to 10-by-10 pixels
于 2012-08-29T15:50:29.690 に答える
0

は のスケールにあるのに対し、はgrayのスケールにあるためです。これにより、 の大きな配列が発生します。問題を解決する変更されたコードは次のとおりです。[0,1]threshold[0,256]lbwfalse

load trees % from MATLAB
gray=rgb2gray(map); % 'map' is loaded from 'trees'. Convert to grayscale.
threshold=128/256;
lbw=double(gray>threshold);
BW=im2bw(X,lbw); % 'X' is loaded from 'trees'.
imshow(X,map), figure, imshow(BW)

結果は次のとおりです。

ここに画像の説明を入力

于 2012-08-29T15:50:08.693 に答える