忍者ブログ

設備のマニアどっとこむ

IoT開発、設備・DIYのブログ!

opencvでAI学習用画像の作成

最近画像データをAIに入れていろいろやっているのですが、サイズであったりビット数であったり
制限が多いです。今日はメモとしてopencvを使った画像処理をまとめてみました。
※opencvをインストールしている前提となります。参考にした記事




①動画から1コマずつの画像に変換するコード
import cv2
import os
def save_all_frames(video_path, dir_path, basename, ext='jpg'):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return
    os.makedirs(dir_path, exist_ok=True)
    base_path = os.path.join(dir_path, basename)
    digit = len(str(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))))
    n = 0
    while True:
        ret, frame = cap.read()
        if ret:
            
            cv2.imwrite('{}{}.{}'.format(base_path, str(n).zfill(digit), ext), frame)
            n += 1
        else:
            return
save_all_frames('動画のpath', '出力する画像のpath', 'ファイル名', 'png')


②画像をグレースケールで読み込み、リサイズするコード
import cv2
img = cv2.imread('読み込む画像のpath/ファイル名')
width,height=100,100
img = cv2.resize(img,(width, height))
cv2.imwrite('出力する画像のpath/ファイル名’)

③さらに2値化するコード
import cv2
img = cv2.imread('読み込む画像のpath/ファイル名')
width,height=100,100
img = cv2.resize(img,(width, height))
threshold = 100
ret, img_thresh = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
ret,img_otsu = cv2.threshold(img,0,255,cv2.THRESH_OTSU)
cv2.imshow("img_otsu",img_otsu)
cv2.imwrite("出力する画像のpath/ファイル名",img_otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()


③000.png、001.pngといった連続する画像を順番にリサイズ、2値化するコード
 (100個まで)
import cv2
import numpy as np
for i in range(100):
  img = cv2.imread("読み込む画像のpath/{0:03d}.png".format(i), cv2.IMREAD_GRAYSCALE)
  width,height=100,100
  img = cv2.resize(img,(width, height))
  threshold = 100
  ret, img_thresh = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
  ret,img_otsu = cv2.threshold(img,0,255,cv2.THRESH_OTSU)
  #cv2.imshow("img_otsu",img_otsu)
  cv2.imwrite("出力する画像のpath/%03.f"%(i)+".png",img_otsu)
  
Mnistとか基本データセットであることが多いので自前のデータを扱う場合はopencvはマストです!!






拍手[0回]

PR

コメント

翻訳(Translate)

プロフィール

HN:
佐々木 雅史
性別:
男性
自己紹介:
2021年 ラズパイ、M5stackを用いたIoT開発を専門で受注するアルティメンテを設立。代表を務める。
・2020年ラズパイコンテスト優良賞受賞
・設備系資格多数(電験3種、消防設備士甲4、2級ボイラー技士、危険物乙4、電工2種、技術士補(電気・電子)、エネ電、フォークリフトなど)

AD

カレンダー

02 2024/03 04
S M T W T F S
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31