Monday, April 18, 2022

How to convert images to dataset Python

 Code 1

(.env) [boris@fedora35server PILLOW]$ cat imageShow.py

# load and display an image with Matplotlib

from matplotlib import image

from matplotlib import pyplot

# load image as pixel array

image = image.imread('coala.jpeg')

# summarize shape of the pixel array

print(image.dtype)

print(image.shape)

# display the array of pixels as an image

pyplot.imshow(image)

pyplot.show()





























Code 2

(.env) [boris@fedora35server PILLOW]$ cat imageToNDArray.py

from PIL import Image
from numpy import savetxt
from numpy import savez_compressed
from numpy import asarray


# load the image
image = Image.open('coala.jpeg')

# convert image to numpy array
data = asarray(image)
print(type(data))
print(data)

# unload 3D array to files via reshape
savetxt("data.txt", data.reshape((3,-1)), fmt="%s", header=str(data.shape))
savez_compressed("data.npz", data.reshape((3,-1)), fmt="%s", header=str(data.shape))
print("Both Unloads data done")


# summarize shape
print(data.shape)

# create Pillow image
image2 = Image.fromarray(data)
print(type(image2))
# summarize image details
print(image2.mode)
print(image2.size)

(.env) [boris@fedora35server PILLOW]$ python imageToNDArray.py
<class 'numpy.ndarray'>
[[[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [113 106  52]
  [113 106  52]
  [114 107  53]]

 [[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [113 106  52]
  [113 106  52]
  [114 107  53]]

 [[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [112 105  51]
  [113 106  52]
  [113 106  52]]

 ...

 [[139 118  71]
  [136 115  68]
  [130 109  62]
  ...
  [ 67  91  91]
  [ 68  89  90]
  [ 66  88  86]]

 [[150 128  81]
  [143 121  74]
  [134 111  67]
  ...
  [ 73  93  91]
  [ 69  89  87]
  [ 65  85  83]]

 [[151 127  81]
  [144 120  74]
  [135 111  67]
  ...
  [ 74  93  91]
  [ 70  89  85]
  [ 66  85  81]]]
(450, 800, 3)
<class 'PIL.Image.Image'>
RGB
(800, 450)

Можно получить CSV сразу через 2-ух цветовую гамму

(.env) [boris@fedora35server PILLOW]$ cat imageToCSV.py
from PIL import Image
import numpy as np
import sys
import os
import csv

#Useful function
def createFileList(myDir, format='.jpeg'):
  fileList = []
  print(myDir)
  for root, dirs, files in os.walk(myDir, topdown=False):
      for name in files:
         if name.endswith(format):
              fullName = os.path.join(root, name)
              fileList.append(fullName)
  return fileList

# load the original image
myFileList = createFileList('./')

for file in myFileList:
    print(file)
    img_file = Image.open(file)
    # img_file.show()

    # get original image parameters...
    width, height = img_file.size
    format = img_file.format
    mode = img_file.mode

    # Make image Greyscale
    img_grey = img_file.convert('L')
    img_grey.save('result.png')
    img_grey.show()

    # Save Greyscale values
    value = np.asarray(img_grey.getdata(), dtype=int).reshape((img_grey.size[1], img_grey.size[0]))
    value = value.flatten()
    print(value)
    with open("img_pixels.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(value)































(.env) [boris@fedora35server PILLOW]$ python imageToCSV.py
./
./coala.jpeg
[24 24 24 ... 87 83 79]
(.env) [boris@fedora35server PILLOW]$ ll
total 4680
-rw-r--r--. 1 boris boris   44769 Apr 18 10:42 coala.jpeg
-rw-rw-r--. 1 boris boris     318 Apr 18 10:49 imageShow.py
-rw-rw-r--. 1 boris boris    1071 Apr 18 13:44 imageToCSV.py
-rw-rw-r--. 1 boris boris     691 Apr 18 13:33 imageToNDArray.py
-rw-rw-r--. 1 boris boris 2514008 Apr 18 13:52 img_pixels.csv
-rw-rw-r--. 1 boris boris  144709 Apr 18 13:52 result.png

Преобразование изображения с помощью Keras API

(.env) [boris@fedora35server PILLOW]$ cat imageConvTF.py
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import array_to_img
from tensorflow.keras.preprocessing.image import save_img

# load the image
img = load_img('coala.jpeg')
print("Orignal:" ,type(img))
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
img.show()

# convert to numpy array
img_array = img_to_array(img)
print("NumPy array info:") 
print(type(img_array))    

print("type:",img_array.dtype)
print("shape:",img_array.shape)
print(img_array)
# convert back to image

img_pil = array_to_img(img_array)
print("converting NumPy array:",type(img_pil))































References

No comments:

Post a Comment