機械学習の時間だよ

ワイのスマホ画像を見ていただきたい
f:id:elve:20220115074516p:plain
条件反射的にスクショしてるピクミンの画像が散見される。コレをどうにかしてまとめたい。

というわけで、機械学習です
結論:まだできてません。
Google Colab
で動かしますよー

ベース

note.com

コレの更にベースが書き直されて新しくなってたのでこっち見ればよかった(ノД`)ナェルシク 色々エラー出て大変だった。
zenn.dev

概要

f:id:elve:20220115080054p:plain
この学習用ファイルにある画像で学習して
テスト画像をピクミンかどうか区別したい

ピクミン学習用
f:id:elve:20220115081302p:plain

その他学習用
f:id:elve:20220115081308p:plain

ソース

一応動く。でも全部その他の画像と判断するorz

import tensorflow.keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Dense, Dropout
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers import Adagrad
from tensorflow.keras.optimizers import Adam
from tensorflow import keras
import numpy as np
from PIL import Image
import os
image_list = []
label_list = []
# 学習データ読み込み
for dir in os.listdir("./drive/MyDrive/img/"):
dir1 = "./drive/MyDrive/img/" + dir
print(dir1 + ": ")
print(len([name for name in os.listdir(dir1)
if os.path.isfile(os.path.join(dir1, name))]))
if dir == "学習用ピクミン画像":
label = 0
elif dir == "学習用その他":
label = 1
else:
# テスト用はなんもしない
print(dir + ": dir")
continue
for file in os.listdir(dir1):
# 1
label_list.append(label)
filepath = dir1 + "/" + file
# 2
try:
# dtypeどうのってエラー出たので適当に追加 RGBじゃない写真とかでコケたので追加
image = np.array(Image.open(filepath).convert(
"RGB").resize((25, 25)), dtype='uint32')
except:
print(file+":1")
# 3
try:
image = image.transpose(2, 0, 1)
except:
print(file+":2")
# 4
try:
image = image.reshape(
1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0]
except:
print(file+":3")
# 5
try:
image_list.append(image / 255.)
except:
print(file+":4")
image_list = np.array(image_list)
Y = to_categorical(label_list)
# モデル構築
# 1
model = Sequential()
# 2
model.add(Dense(200, input_dim=1875))
model.add(Activation("relu"))
model.add(Dropout(0.2))
# 3
model.add(Dense(200))
model.add(Activation("relu"))
model.add(Dropout(0.2))
# 4
model.add(Dense(2))
model.add(Activation("softmax"))
opt = Adam()
model.compile(loss="categorical_crossentropy",
optimizer=opt, metrics=["accuracy"])
# 学習
model.fit(image_list, Y, epochs=1500, batch_size=100, validation_split=0.1)
# 判断
dir1 = "./drive/MyDrive/img/テスト用"
for file in os.listdir(dir1):
filepath = dir1 + "/" + file
if os.path.isdir(filepath):
# ディレクトリは何もしない
continue
# ここは怒られなかったのでRGBだけ。謎
image = np.array(Image.open(filepath).convert("RGB").resize((25, 25)))
image = image.transpose(2, 0, 1)
image = image.reshape(
1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0]
# image.reshape が使えなくなってて大騒ぎ
result = np.argmax(model.predict(np.array([image / 255.])), axis=1)
if result == 0:
# ピクミン画像 来なかった・・・
print('pic!')
try:
os.rename(filepath,
dir1 + "/ピクミン/"+file)
except OSError as err:
print("OS error: {0}".format(err))
except:
print(os.error)
else:
# その他の画像
try:
os.rename(filepath,
dir1 + "/その他/"+file)
except OSError as err:
print("OS error: {0}".format(err))
except:
print(os.error)

今後

25*25で判断できないのであろうが、大きくしたらエラーが出て意味不明だったので別の方法を考えるw

参考

OpenCVとPythonとVisualStudioで顔認識してみる │ Kazuki Room ~ モノづくりブログ ~
【TensorFlow/Keras入門】ディープラーニングを簡単に手を動かして学ぼう | 西住工房
Tensorflow/Kerasのインストール方法(Windows、Mac編) | 西住工房
【Python版OpenCV】Haar Cascadeで顔検出、アニメ顔検出、顔にモザイク処理 | 西住工房
【Python/OpenCV】SVMで画像分類①(手書き数字編) | 西住工房
お手軽Python! Colaboratory よくあるエラーメッセージ|プログランマ|note
python:機械学習で梨と林檎を分類する|tamurasann|note
python:恥ずかしいので機械にエロ画像を仕分けしてもらう(畳み込み処理)|tamurasann|note
NumPyのデータ型dtype一覧とastypeによる変換(キャスト) | note.nkmk.me
Python, NumPyで画像処理(読み込み、演算、保存) | note.nkmk.me
Python – オブジェクトを格納するNumpyのndarrayをインターフェイスする方法は?
Python – Tensor Flow 2.0、KerasのConv2Dレイヤーでinput_shapeを指定する方法
【Python】簡易的な仕分け機能付き画像ビューワー作ってみた – Qiita
PythonとOpenCVを使って物体検出をやってみた – Qiita
OpenCV+pythonで機械学習をやってみた③_実践編 | シンギュラリティ・ラボ
python – mnist CNN ValueError expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28] – Stack Overflow
Pythonを使用した画像認識方法をわかりやすく解説!API3つも紹介 – IT業界、エンジニア、就活生、第二新卒、転職者、20代向け情報サイト
OpenCV 入門:画像処理・画像認識・機械学習の実装を徹底解説(全実装コード公開)
python : model.predict_classesは推奨されていません -代わりに使用するものは何ですか?
【初心者向け】Pythonのcontinue文について解説!break文との違いは | TechTeacher Blog
python — Google colabファイルのダウンロードでエラーを取得できませんでした

どのくらい面白かった?

星を押して送信してね

平均 0 / 5. Vote count: 0

是非フォローしてください

最新の情報をお伝えします

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です