How to convert RGB image to Luminance image and store the image as .raw file in Matlab - image

i am trying to convert an RGB image to a Luminance image and save it as a .raw image to use it in another software. I am using the following code
m = imread('20x20-alpha1-1.jpg');
out = zeros(1942,2588);
for i=1:1942
for j=1:2588
out(i,j) = 0.2126*m(i,j,1) + 0.7152*m(i,j,2) + 0.0722*m(i,j,3);
end
end
fileID = fopen('20x20-alpha1-1.raw');
fwrite(fileID,out);
fclose(fileID);
However, when I try to open the image with IrfanViewer, the file is said to be corrupted. Is it a problem in my code ? If so how can I convert this image to Luminance image and save it ?
Thank you :)

There is no need to mess around with .raw files in this case. Write a tiff file instead:
imwrite(out,'20x20-alpha1-1.tiff','tiff')

Related

How to open a raw YCbCr image file in MatLab?

I am trying to open a 1920x1080 YCbCr raw image file in Matlab, however I am having difficulties getting the following code below to work:
fid = fopen(filePath);
image = fread(fid, 1920*1080, 'uint8=>uint8');
fclose(fid);
image = reshape(image, 1080, 1920);
However, when I go to show the image, it does not look as expected.
The actual image should be colour, however I get a strange black and white image, not resembling the expected output at all.
I have also tried loading it into a 3D array, with each dimension representing one of the Y, Cb and Cr channels, however this also produced a similar output as described before.
Any help would be appreciated.
Ignore this bit and look below at the EDIT:
I don't understand why you are using fread? Why not use imread,
which is mean't for reading images? Using this infamous original
image, as a base for my test script, I could display a YCbCr
image, as shown in the little script below.
original = imread("lenna.jpg");
% figure, imshow(original); % if you want to see how the original image looks
YCbCr_version = rgb2ycbcr(original);
% figure, imshow(YCbCr_version); % if you want to see how the YCbCr image looks
imwrite(YCbCr_version, "out.jpg");
YCbCr_fromFile = imread("out.jpg");
figure, imshow(YCbCr_fromFile);
EDIT:
IF however you have a binary version of the file and can only read it using using fread,
then the following script should work,
clc;
clear;
close all;
original = imread("lenna.jpg");
% figure, imshow(original); % if you want to see how the original image looks
YCbCr_version = rgb2ycbcr(original);
% figure, imshow(YCbCr_version); % if you want to see how the YCbCr image looks
fileID = fopen('out.bin','w');
fwrite(fileID, YCbCr_version, 'uint8');
fclose(fileID);
fileID = fopen('out.bin','r');
fromFile = fread(fileID, 512*600*3, 'uint8=>uint8');
fclose(fileID);
image = reshape(fromFile, 512, 600, 3);
imagesc(image)
The point is, in the read operation, you have to give the 3 channels in the multiplier also, as color images have this 3rd dimension, i.e. 512*600*3. If you only give 512*600, as you were doing, you would have no color info. Also the reshape function would need to be changed to take into account the 3rd dimension. Hence, reshape(fromFile, 512,600, 3).
YCbCr version loaded from the file
As you said "Any help would be appreciated", I thought I would mention you can simply convert a raw YCbCr file to PNG, TIFF, JPEG or any other format file with ImageMagick which is installed on most Linux distros and is available for macOS and Windows.
Start a Terminal, (or Command Prompt if under Windows), and convert the YCbCr image.raw to PNG with:
magick -size 1920x1080 -depth 8 YCbCr:image.raw result.png
Or, say a CCIR 601 YUV file to NetPBM PPM format:
magick -size 800x600 -depth 8 YUV:image.raw result.ppm

Saving a generated image on Matlab Gui

I am trying to save an image that I generated on a Matlab Gui. I tried following code with a push button:
[Save,savename] = uiputfile('*.bmp','Save Figure As...')
fname=fullfile(savename,Save);
imwrite(handles.axes2, 'fname', 'bmp');
It doesn't work. Can anyone please help?
imwrite is for saving image data (as a matrix) to an image file. If you want to save the figure, you will want to use saveas.
If you need to save an image of a specific axes, you can use getframe to save a screenshot of the specified axes, then convert this to an image using frame2im and then use imwrite to save this image data to a file.
frame = getframe(handles.axes2);
im = frame2im(frame);
imwrite(im, fname)

Save output image in matlab window to image

I have a image and some contours as bellow figure. I want to save the output into image (png or jpg). The saved image only contains the image region without the matlab window. Let see my example in the figure. Could you have me implement it by matlab? This is my code to make output figure
img = imread('coins.png');
mask_red=zeros(size(img));
mask_green=zeros(size(img));
mask_red(30:160,40:170)=1;
mask_green(70:100,60:130)=1;
imagesc(uint8(img),[0 255]),colormap(gray),axis off;axis equal,
hold on;
[c1,h1] = contour(mask_red,[0 0],'r','Linewidth',3);
[c2,h2] = contour(mask_green,[0 0],'g','Linewidth',3);
hold off;
%% Save output figure
Use the getframe and cdata idiom. If the figure is open, simply do this:
f = getframe;
im = f.cdata;
im will contain the image that was contained inside your frame as a RGB image. Running your code in your post, then the above code, then doing imshow(im), we get:
If you want to save the image, just use imwrite:
imwrite(im, 'coins_final.png');
The image will be saved in a file called coins_final.png.

How to Save an image in matlab

I use the below command to display the image
imshow(img,[]);
when i use the following command to save the image it is saved as an empty white page
imsave;
how to save the image in this case any command would do
You are probably running into an issue with matrix type and range. If img is type double it needs to be scaled between 0 and 1.
A common issue is to load an image in uint8 (scaled between 0 and 255), convert to double in order to do some processing on it, without scaling, and then try and save it out. When you do that, MATLAB tries to convert back to uint8, and any values in the image outside the [0 1] range are clipped. On many images this means that the file comes out all white.
To get around this, use functions like im2double and im2uint8 rather than just double or uint8 when converting images.
Try at the command line the difference between:
img = imread('pout.tif');
img = double(img);
imshow(img,[]);
imsave;
and
img = imread('pout.tif');
img = im2double(img);
imshow(img,[]);
imsave;
Convert image data into an actual image and try again:
h = image(img); %Convert to object
imsave(h); %Save image object
Notice that if you close the figure window generated by image(), the object is deleted and the handle has will point to nothing. Though this may be beyond of what you are asking for.
Hope this adjustment solved your problem
First convert the image to rgb using
img1=label2rgb(img);
then again convert the image into an gray image using
img2=rgb2gray(img1);
then u can use imshow to show the image and save it using imsave
imshow(img2);
imsave();

MATLAB - write image into an eps file

In MATLAB, how do you write a matrix into an image of EPS format?
It seems imwrite does not support EPS.
Convert is not working on the Linux server I am using:
$ convert exploss_stumps.jpg exploss_stumps.eps
convert: missing an image filename `exploss_stumps.eps' # convert.c/ConvertImageCommand/2838
Why?
I tried gnovice's idea under terminal mode:
figH = figure('visible','off') ;
imshow(img,'border','tight',... %# Display in a figure window without
'InitialMagnification',100); %# a border at full magnification
print(strcat(filepath,'/', dataset,'_feature_',num2str(j), '.eps'),'-depsc2');
close(figH) ;
However I got:
??? Error using ==> imshow at 191
IMSHOW requires Java to run.
Error in ==> study_weaker at 122
imshow(img,'border','tight',... %# Display in a figure window without
191 error(eid,'%s requires Java to run.',upper(mfilename));
How can I fix it?
One possible solution is to plot your image using IMSHOW, then print the entire figure as a .eps using PRINT:
img = imread('peppers.png'); %# A sample image
imshow(img,'Border','tight',... %# Display in a figure window without
'InitialMagnification',100); %# a border at full magnification
print('new_image.eps','-deps'); %# Print the figure as a B&W eps
One drawback to this solution is that if the image is too big to fit on the screen, IMSHOW will shrink it to fit, which will reduce the on-screen resolution of the image. However, you can adjust the final resolution of the saved image using the -r<number> option for the PRINT function. For example, you can print your figure as an Encapsulated Level 2 Color PostScript with a resolution of 300 dpi by doing the following:
print('new_image.eps','-depsc2','-r300');
EDIT: If you are unable to use IMSHOW (either because you don't have the Image Processing Toolbox or because you are using a MATLAB mode that doesn't allow it), here is an alternative way to create and print the figure:
img = imread('peppers.png'); %# A sample image
imagesc(img); %# Plot the image
set(gca,'Units','normalized',... %# Set some axes properties
'Position',[0 0 1 1],...
'Visible','off');
set(gcf,'Units','pixels',... %# Set some figure properties
'Position',[100 100 size(img,2) size(img,1)]);
print(gcf,'new_image.eps','-depsc2','-r300'); %# Print the figure
You can also take a look at this documentation to see how printing works without a display.
It should work using imwrite. You would have to add a colormap for it to work though.
However, ckecking the help pages I see that it is NOT possible to use imwrite to write an EPS file.
Following code may help you to convert png file to eps.
fileName = 'FarmerStats'; % your FILE NAME as string
A = imread(fileName,'png');
set(gcf,'visible','off') %suppress figure
image(A);
axis image % resolution based on image
axis off % avoid printing axis
set(gca,'LooseInset',get(gca,'TightInset')); % removing extra white space in figure
saveas(gcf,fileName,'epsc'); % save as COLOR eps file

Resources