Read an RGB image file and save it in grayscale and CSV format It seems to be a niche in demand, so the color of my personal notes is strong.
google colaboratory
https://newtechnologylifestyle.net/%E7%94%BB%E5%83%8F%E3%83%87%E3%83%BC%E3%82%BF%E3%81%8B%E3%82%89numpy%E5%BD%A2%E5%BC%8F%E3%81%AB%E5%A4%89%E6%8F%9B%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95/ I used it as a reference.
from PIL import Image
import os, glob
import numpy as np
#Please adjust here to your environment
files = glob.glob(path + "/" + class_names[1] + "/" + "*.png ")
img_list = []
image = Image.open(files[0])
# image = image.convert("RGB")
image = image.convert("L")
data = np.asarray(image) # <class 'numpy.ndarray'> (33, 13, 3)
print(data)
print(type(data))
print(data.shape)
from matplotlib import pyplot as plt
plt.imshow(data, cmap="gray")
plt.show()
img_list.append(data) # <class 'list'>
print(type(img_list))
img_list = np.array(img_list) # <class 'numpy.ndarray'> shape(1, 33, 13, 3)
plt.imshow(img_list[0], cmap="gray")
plt.show()
import pandas as pd
df = pd.DataFrame(data)
save_path = drive_root_dir + "/xxxxxxx/data/" + "train.csv"
df.to_csv(save_path, encoding="")
After this, add the process of adding images to img_list. The third 3 in (33, 13, 3) represented RGB. I finally understood.
I want to make it the train.csv data of the image, so I am modifying the place where I append it to the list type and add it. This code also has a strong personality for my notes, so I leave a comment out for confirmation.
from matplotlib import pyplot as plt
from PIL import Image
import os, glob
import numpy as np
files = glob.glob(path + "/" + class_names[1] + "/" + "*.png ")
img_list = []
for i, file in enumerate(files):
image = Image.open(file)
image = image.convert("L")
data = np.asarray(image) # <class 'numpy.ndarray'> (33, 13, 3)
# print(data)
# print(type(data))
# print(data.shape)
# plt.imshow(data, cmap="gray")
# plt.show()
img_list.append(data) # <class 'list'>
# print(type(img_list))
# img_list = np.array(img_list) # <class 'numpy.ndarray'> shape(1, 33, 13, 3)
plt.imshow(img_list[i], cmap="gray")
plt.show()
if i == 3: #I just want to test it so I'm breaking
break
import pandas as pd
df = pd.DataFrame(img_list)
save_path = drive_root_dir + "/xxxxx/data/" + "train.csv"
df.to_csv(save_path, encoding="")
print("end")
Recommended Posts