10

I can't figure out how to display a raw image which contains 640x480 pixel information, each pixel 8 bit. (Gray image)

I need to go from an np array to Mat format to be able to display the image.

#!/usr/bin/python
import numpy as np
import cv2
import sys
# Load image as string from file/database    
fd = open('flight0000.raw')
img_str = fd.read()
fd.close()

img_array = np.asarray(bytearray(img_str), dtype=np.uint8)

img = ... Conversion to Mat graycolor

cv2.imshow('rawgrayimage', img)
cv2.waitKey(0)

It so confusing with the cv, cv2. I have been trying for a while now, but I can't find the solution.

3 Answers 3

18

.RAW files are not supported in OpenCV see imread,

But the file can be opened with Python and parsed with Numpy

import numpy as np
fd = open('flight0000.raw', 'rb')
rows = 480
cols = 640
f = np.fromfile(fd, dtype=np.uint8,count=rows*cols)
im = f.reshape((rows, cols)) #notice row, column format
fd.close()

This makes a numpy array that can be directly manipulated by OpenCV

import cv2
cv2.imshow('', im)
cv2.waitKey()
cv2.destroyAllWindows()
Sign up to request clarification or add additional context in comments.

1 Comment

Note: my example parses a grayscale image - modify the count argument and reshape function accordingly for a color image
-1
#!/usr/bin/python
#code to display a picture in a window using cv2
import cv2

cv2.namedWindow('picture',cv2.WINDOW_AUTOSIZE)
frame=cv2.imread("abc.jpg")
cv2.imshow('picture',frame)
if cv2.waitKey(0) == 27:
        cv2.destroyAllWindows()

1 Comment

The user specified they are dealing with RAW images not JPEGs
-2

Just an example if you want to save your 'raw' image to 'png' file (each pixel 32 bit, colored image):

import numpy as np
import matplotlib.pyplot as plt

img = np.fromfile("yourImage.raw", dtype=np.uint32)
print img.size #check your image size, say 1048576
#shape it accordingly, that is, 1048576=1024*1024
img.shape = (1024, 1024)

plt.imshow(img)
plt.savefig("yourNewImage.png")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.