1

I have an image save as pippo.dat , I want read it and work on it, the dimensions of the image are 368 x 600 pixel. How should I do? I tried to use Numpy.readtxt but it doesn't work. I am a beginner.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Chiara C
  • 11
  • 1
  • 2
    How did you create the file? – mkrieger1 Oct 08 '21 at 19:23
  • 1
    `.dat` is a meaningless extension often used to mean just "data" in some custom format. You will need to know how the data was written in order to make sense of it. – Thomas Oct 08 '21 at 19:24
  • file extensions are of little indication as to what the file actually contains. I could rename myzip.zip file to myzip.jpeg, doesn't magically make it into an image. What is actually inside this ".dat"? – ch4rl1e97 Oct 08 '21 at 19:24
  • Maybe share the file using Dropbox or Google Drive. – Mark Setchell Oct 08 '21 at 19:32

1 Answers1

0

Aside from the confusing file extension discussed in the comments; Numpy alone doesn't really support images as such, and trying to use loadtxt on one will just produce a mess if it even works at all.

What we can do is use another library like Pillow that does understand images, and create a Numpy array using that. firstly you'll need to install Pillow pip install Pillow

from PIL import Image
import numpy as np
# Open the image
image = Image.open('myimage.jpg')  # swap name as needed
print("Your image's size is", image.size)
# show the image in a window. You can delete this line if you like. 
image.show()
# convert it to a numpy array:
data = np.asarray(image)

And now data is a 3D numpy array of the image, the first 2 dimensions being X and Y pixels, and the 3rd being the colour values ([R,G,B] or [R,G,B,A] if its got an alpha/transparency channel. You can check with image.mode) (if you get a 'weird' palette or grayscale mode like P or L then read this answer: https://stackoverflow.com/a/52307690/9311137 on converting/handling)

ch4rl1e97
  • 666
  • 1
  • 7
  • 24