Convert a PNG file to matrix - image-conversion

I need help in converting a png image back to the original values calculated in MATLAB. I originally downloaded a RADAR image and used xlim & ylim to to plot a zoomed area, then I used the command line (saveas(gca, [opath 'VS',num2str(k),'L',num2str(LL)], 'png')) to save the image to a png file. Now, I am trying to take the png file and convert it back to the original pre-saved matrix. The problem is I do not get the exact values back, as I originally had. I have a couple of colleagues who have also tried and we cannot get the original numbers. Can anyone help? I can provide a pre-saved matrix, lat & lon file (1832 x 720), the plot routine that I use xlim & ylim, the save line, then the routine that takes the png file and tries to return it to the original pre-saved plotted size.
for i=1%:length(tt)
imgpath2=[imgpath tt(i).name];
map=colormap(jet(256));
RGB=imread(imgpath2);
S=rgb2ind(RGB,map);
S=double(S);
L=size(map,1);
out=interp1(1:L,linspace(min_org,max_org,L),S(:,:));
%Turns white spaces into NaNs
out(out==27.176470588235293)=NaN;
% pixels around campus
ave=nanmean(nanmean(out(cam_wid,cam_len)));
testR=out(cam_wid,cam_len);
testR2=10.^(testR./10);
br=nanmean(testR2(:));
rr(i)=(br/300)^(1/1);
end

Related

Problems with extracting a watermark

I'm working on watermarking and recently I try to developp the method found here for a blind color watermarking. For embedding the watermark every is Ok I got great results but in extraction part I don't know why I have a black watermark image and it doesn't look like the original one!! Here is the code I use for extraction:
function extracted_mark=extract_dyn_U(rgb_wateramrked,ix,iy);
% rgb_wateramrked=imread('Watermarked_rgbImage.jpg'); %%% read original image
img=rgb2ycbcr(rgb_wateramrked); %%%convert to ycbcr color space
imgy=img(:,:,1);
imgcb=img(:,:,2);
imgcr=img(:,:,3);
[ca1,ch1,cv1,cd1]=dwt2(imgy,'haar'); %%% Apply dwt 2level on ca
[ca2,ch2,cv2,cd2]=dwt2(ca1,'haar');
[m n]=size(ca2);
blocksize=m/32
%********************Extraction**********************
watermark1=zeros(32,32); % define a zero matrix with the original watermak size
for k=1:32
for j=1:32
L=zeros(4,4);
L=ca2(ix:ix+blocksize-1,iy:iy+blocksize-1);
[U,S,V]=svd(L);
if abs(U(2,1))>= abs(U(3,1))
watermark1(k,j)=1;
else
watermark1(k,j)=0;
end
end
end
imshow(watermark1);
extracted_mark=watermark1;
end
end
It just doesn't give me the right extracted watermark :( and in this work I tried with a binary image from the beginning, but I actually need to convert a color watermark from RGB to decimal then to binary so I can use it. and the issue I got too is when I will have an extracted watermark how to reconverted from binary to decimal then RGB!! thank you in advance
This is th original binary watermark (left) and the result after extraction (right). I expect to have an extracted watermark as the original one.

Saving grayscale image as it appears in jet colormap

I have grayscale satellite image which is processed from spectral data (band classifications). If i use jet colormap in imshow it will show absolute colormapped image. But if i try to imwrite in particular place it is saved like a bluish image. I saw one example in matlab central, but i didnt get. can anyone help me to write my image with colorscaled image.
Matlab central link: http://www.mathworks.in/matlabcentral/answers/25026-saving-grayscale-image-as-it-appears-in-jet-colormap-of-imagesc
there accepted answer link is : http://www.mathworks.com/matlabcentral/fileexchange/7943
I have tried many times, this will show colormaped images in plots (imshow) they didnt write anywhere with colormaped. Now i want to write my image with colormaped.
example code:
I= imread('image path');
imshow(I,'colormap',jet);
imwrite(I,'path','jpg'); /not working
or
imwrite(I,jet,'path','jpg'); /not working
Please help to solve this issue.
When you use imshow the colormap is always adjusted to the range of values in your image. imwrite however assumes your image has a value range of [0,1] if you are using single or double data types. Try to scale your image to the range [0,1] before saving.
If you provide a colormap in the call to imwrite, MATLAB assumes you are using an indexed image. Thus you will have to convert the image to the indexed format first. The following snippet worked for a test image I of mine:
% scale to [0,1]
I = I - min(I(:));
I = I ./ max(I(:));
% Create indexed image
[J,~] = gray2ind(I);
% Save image
imwrite(J,jet,'path','jpg');
Solution by hbaderts worked well for me, but later I found out that some images were still scaled slightly different way from imshow.
However, I might found a reason of an original problem. Just after Matlab starts, its default colormaps (including 'jet') are set to 64 colors (64x3). Then, if any image is shown with a colormap, for example if imshow('cameraman.tif'), colormap('jet') is executed, all default colormaps become 256x3 (can be verified with jetMap=jet; before and after). Then it might happen that an image was written with a colormap different from the one applied to image figure (for example, if a figure called after imwrite).
Finally I found this solution (no image pre-scaling needed):
% Create indexed image, explicitly using 256 colors
imInd=gray2ind(im,256);
% Convert indexed image to RGB using 256-colors jet map
jetRGB=ind2rgb(imInd,jet(256));
% Save image
imwrite(jetRGB,'jet.png');
The images I used have the same color scale now, both the saved one and the one shown in figure.

Matlab: pixel values of multiple .jpg images

I have a couple hundred images like this one:
They are in a single folder and am trying to figure out a way in Matlab to automatically analyze each image's pixel values at point (700,755). I know how to do this one-at-a-time, as such:
rgb=impixel(p,700,755)
This returns the red-green-blue values at that particular point for the image. I'm very new to Matlab...what piece of code would analyze each image in the folder and save the RGB value on separate lines in a table/array?
Also, I have selected an area using the pixel region tool: '[696.463836477986 750.095011390851 19.9889937106933 13.3672527600921]' How do I analyze all the pixel values in that area and get the statistics (min, max, mean, etc.)...plus do that for all 200 images I have in the folder?
I appreciate the help!
AP
impixel can work for all the image as well:
impixel(I)
or for a specific (pixel) column and row:
impixel(I,c,r)
But you need first to read the image into a matrix. The imread function, returns all the RGB data of an image in an array:
A = imread(filename, fmt)
it reads a grayscale or color image from the file specified by the string filename. A is an array containing the image data. If the file contains a 'grayscale' image, A is an 'M-by-N' array. If the file contains a 'truecolor' image, A is an 'M-by-N-by-3' array. (3: R-G-B)
To read a bunch of files in a folder do this:
files = dir('*.jpg');
for i=1:length(files)
eval(['imread ' files(i).name]);
end
You can use imcrop function to crop the images you have:
using mouse:
I2 = imcrop(I)
or using dimensions:
I2 = imcrop(I,[75 68 130 112]);

PyGame Poor Image Quality & Gradient Banding

I noticed that when displaying jpg or png images they look alot like a GIF file in that there is limited colors and "banding".
You can see the original and a screenshot attached. Kinda hard to tell scaled down but you can see it.
Actually better example. See the banding around the circle?
Here is my code:
#pygame code to render an image
import pygame, os
import time
image = 'gradient-test.png' #located in same folder as this file:resized in Photoshop
pygame.init() #I assume you did this?
SCREEN = pygame.display.set_mode((1366, 768))
pygame.mouse.set_pos((1366, 768))
picture = pygame.image.load(image)
SCREEN.blit(picture,(0,0))
pygame.display.update()
time.sleep(5)
It seems like a problem with the pixel format of your surface. You can add the following lines to your script to see if there's a difference between the pixel format of your image surface and your screen surface:
print 'picture', picture.get_bitsize()
print 'screen', SCREEN.get_bitsize()
It's good practice and recommended to always change the pixel format of any new surface to the pixel format of your screen surface by calling convert():
convert()
change the pixel format of an image
convert(Surface) -> Surface
Creates a new copy of the Surface with the pixel format changed ...
If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times.
It's simple:
picture = pygame.image.load(image).convert() # added convert() call
Also, you can try to set the color depth of your screen manually, like:
SCREEN = pygame.display.set_mode((1366, 768),0, 32) # use 32-bit color depth

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