sparkingmyself
sparkingmyself

Reputation: 148

How to read raw image in Python and plot as an image

I am trying to read a raw image file, but the stored image array seems to be one dimensional. Not sure how to read a raw file and plot it. Any help would be appreciated

Link to image TestImage1c.raw

from scipy import misc
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import math

A = np.fromfile("TestImage1c.raw", dtype='int16', sep="")
print("A.shape: %d", A.shape)
print("A: ", A)
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
print("img_gray :", img_gray)
print("img_gray shape: ", img_gray.shape)
print("img_gray size: ", img_gray.size)
plt.imshow(img_gray, cmap="gray")
plt.show()

OUTPUT:

D:\Python36\python.exe D:/PycharmProjects/First/readrawimage.py
A.shape: %d (1143072,)
A:  [-27746 -24987  26514 ...,  28808 -31403  18031]
img_gray : -20149.59
img_gray shape:  ()
img_gray size:  1
Traceback (most recent call last):
  File "D:/PycharmProjects/First/readrawimage.py", line 33, in <module>
    plt.imshow(img_gray, cmap="gray")
  File "D:\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in 
  imshow
    **kwargs)
  File "D:\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in 
  inner
    return func(ax, *args, **kwargs)
  File "D:\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, 
  in imshow
    im.set_data(X)
  File "D:\Python36\lib\site-packages\matplotlib\image.py", line 604, in 
  set_data
    raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

Process finished with exit code 1

Upvotes: 1

Views: 10900

Answers (1)

sparkingmyself
sparkingmyself

Reputation: 148

I found that RAW file is interleaved with RGB value an is one dimensional array

R(0,0) G(0,0) B(0,0) R(0,1) G(0,1) B(0,1)

.......

A = np.fromfile("TestImage2c.raw", dtype='int8', sep="")

A = np.reshape(A, (756, 1008, 3))
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
plt.imshow(img_gray, cmap="gray")
plt.show()

I started getting the image now.

Thank you all for response.

Upvotes: 3

Related Questions