簡體   English   中英

如何將roipoly在matlab中選擇的點的RGB值寫入文本文件?

[英]How do I write RGB values of points selected by roipoly in matlab to a text file?

我做了:

I = imread('abc.jpg');
BW = roipoly(I);

我試圖獲取創建多邊形時單擊的所有點的像素值。

r= BW(:, :, 1 );
g= BW(:, :, 2 );
b= BW(:, :, 3 );

這不起作用。

最后,我想寫入文本文件:

filename = fullfile('C:\Users\ABC\Documents\MATLAB','test.txt'); 
fid = fopen(filename,'w'); 
fprintf(fid, '%d %d %d', r,g,b);
fclose(fid);

您的問題是,當I是3D時, size(BW)僅為2D。 BW只是一個二進制掩碼,指示通過roipoly選擇了哪些像素。

一個可能的解決方案是使用BW蒙版從I選擇像素:

rI = reshape(I,[],3); %// "flatten" the image
selectedRGB = rI(BW,:);  %// select the pixels in the polygon

現在您可以寫入文件

dlmwrite( fullfile('C:\Users\ABC\Documents\MATLAB','test.txt'), selectedRGB, 'delimiter', ' ');

有關更多信息,請參見dlmwrite


如果您僅對多邊形角點(而不是整個區域)的RGB值感興趣,則可以使用以下代碼

[BW xi yi] = roipoly(I);

現在,您應該忽略代表該區域的BW ,而僅使用xiyi

sel = sub2ind( size(I(:,:,1)), yi, xi ); %// convert indices to linear indices
selectedRGB = rI(sel,:); %// will give you the RGB of the corners only.

或者,您可以使用ginput選擇圖像中的點。

此代碼使用像素坐標在多邊形的角中創建點,創建感興趣區域的遮罩,使用BW遮罩創建該區域的灰度圖像,然后將灰度區域轉換回RGB。 在代碼末尾創建的文本文件包含圖像的Unit8數據。

是否只需要手動指定文本文件的所有坐標?

I = imread('image.jpg'); 


c = [62 95 103 70];  % specify column coordinates (more than 4 if you want)
r = [126 122 193 197]; % specify row coordinates (more than 4 if you want)

BW = roipoly(I,c,r); % convert to binary mask
[R C] = size(BW); 

for i = 1:R
    for j = 1:C
     if BW(i,j) == 1

            outputImage(i,j) = I(i,j); % get grayscale image of the specified region

     else

            outputImage(i,j) = 0; 

     end
    end
end

imtool(outputImage, []); % in imtool you can see that pixels have only one value
rgbBinary = cat(3,outputImage,outputImage,outputImage);  % convert grayscale image to binary rgb
finalImage = im2uint8(rgbBinary); % convert image from double binary rgb (0 1) to unit8 256 value rgb
imtool(finalImage) % analyze image using (Inspect pixel values)

for i = 1:R
    for j = 1:C
     if BW(i,j) == 1
            finalImage(i,j,1)=I(i,j,1);
            finalImage(i,j,2)=I(i,j,2);
            finalImage(i,j,3)=I(i,j,3);
     end
    end
end

imshow(finalImage) % the specified area in rgb


txtdoc = fopen( 'imageData.txt', 'wt' ); % creates txt file if it doesn't exist or overwrites the existing file

  dlmwrite('imageData.txt',finalImage,'delimiter',' ') % writes the data to txt file delimited by space

fclose(txtdoc);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM