1

i have folder with pictures ("C:\Users\Admin\Downloads\mypicture") here example of it 8 and2

i want convert it to pixel dataframe like this

  pixel1 pixel. pixel158 pixel159 pixel160 pixel161 pixel162 pixel163 pixel164 pixel165 pixel166 pixel167 pixel168 pixel169 pixel170 pixel171 pixel172
1      0      …        0      191      250      253       93        0        0        0        0        0        0        0        0        0        0
2      0      …       32        0        0        0        0        0        0        0        0        0        0        0        0        0        0
  pixel173 pixel174 pixel175 pixel176
1        0        0        0        0
2        0        0       16      179

Every image is represented as a single row . The greyscale of each image falls in the range [0, 255]. i do so

img = mpimg.imread("C:\Users\Admin\Downloads\mypicture")
img = np.ravel(img) 
df = pd.DataFrame([img])

but i get this error

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

How can i get desired data frame in csv file?

Julia
  • 141
  • 11

1 Answers1

0

You could Use PIL library to convert the image to a pixel dataframe, by getting the pixel's list from an image like this

from PIL import Image
im = Image.open('image.png')

pixels = list(im.getdata())

this will return a list of pixels with the (r,g,b) values, so if you just want to get the grayscale of each pixel, just iterate the list in the second element of each value, like this

result = []
counter = 0
for pixel in pixels:
    counter += 1
    result.append(['pixel'+ str(counter), pixel[1]])
return (result)

Output:

['pixel1', 72], ['pixel2', 50], ['pixel3', 0], ['pixel4', 11], ['pixel5', 30], ['pixel6', 42], ['pixel7', 107], ['pixel8', 123], ['pixel9', 124], ['pixel10', 130]
Gonzalo Garcia
  • 6,192
  • 2
  • 29
  • 32
  • 1
    im = Image.open('image.png') Here only one picture. I have many pictures, how to show path for my folder with picture and then convert all picture to pixels? – Julia Feb 13 '19 at 10:30
  • You could try using glob https://docs.python.org/3/library/glob.html. Here there is an example: https://stackoverflow.com/questions/26392336/importing-images-from-a-directory-python – Gonzalo Garcia Feb 14 '19 at 12:13