0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

画像をグレースケールにしてからcsvとして保存

Last updated at Posted at 2019-12-17

やりたいこと

RGBの画像ファイルを読み込んで、グレースケールかつCSV形式で保存する
需要としてはニッチだと思われるので、自分用のメモの色合いが強いです。

動作環境

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/
参考にしました。

コード内容

from PIL import Image
import os, glob
import numpy as np

# ここらへんは自分の環境に合わせて下さい
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="")

この後、img_listに画像を追加していく処理を追加します。
(33, 13, 3)の3つ目の3って、RGBを表していたんですね。やっと理解しました。

コードを修正

画像のtrain.csvデータにしたいので、list型にappendして追加しているところを修正してます。このコードも自分のメモ用の性格が強いので、コメントアウトも確認用に残しています。

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:   # テストしたいだけなのでbreakしてます
      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")
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?