1

I have an image in a numpy array which I save using savefig and then use opencv loadImage function to load the image to a CvMat. But I want to remove this saving the image step.

My Numpy Image size is 25x21, and if I use fromArray function like

im = cv.fromarray(asarray(img))

I get a CvMat of size 25x21 which is very small. But When I save the image to png format and load it back using LoadImage, I get the full sized image of size 429x509.

Can somebody please tell me how do I get this full sized image from numpy array to CvMat? Can I convert the image from numpy array to a png format in code without saving it using savefig()? This is what I am doing right now.

imgFigure = imshow(zeros((gridM,gridN)),cmap=cm.gray,vmin=VMIN,vmax=5,animated=True,interpolation='nearest',extent=[xmin,xmax,ymin,ymax])  
imgFigure.set_data(reshape(img,(gridM,gridN)))  
draw()  
fileName = '1p_'
fileName += str(counter)
fileName += ".png" 
savefig(fileName,bbox_inches='tight',pad_inches=0.01,facecolor='black')

The size of img above is 525 and gridM and gridN are 25 and 21.Then I load this image using:

img = cv.LoadImage(fileName, cv.CV_LOAD_IMAGE_GRAYSCALE)

Now img size is 429x509.

shobhit
  • 89
  • 2
  • 8
  • Welcome to SO :) If my answer doesn't help, please show your code identifying what the trouble is, cheers. – fraxel Jun 09 '12 at 08:00
  • @fraxel I wasnt able to format code correctly in comment so edited the question and added my code there. – shobhit Jun 11 '12 at 00:43

1 Answers1

1

You can just use cv.fromarray() directly upon your numpy array with no need to save inbetween:

import cv
import numpy as np
a = np.arange(0,255,0.0255).reshape(50,200)
b = cv.fromarray(a)
cv.SaveImage('saved.png', b)
print b
#Output:
<cvmat(type=42424006 64FC1 rows=50 cols=200 step=1600 )>

The numpy array becomes a cvmat, and the size is unchanged. This is the saved image:

enter image description here

fraxel
  • 34,470
  • 11
  • 98
  • 102