画像ファイル読込、書込み imread、imwrite - OpenCV、Python徹底解説
OpenCVで簡単にイメージファイルの読込、書込みの方法です。
基本形
画像読込
※ この方法だと、実はアスキー以外のファイル名は扱えません。
下の方で詳しく記載します。
import cv2
img = cv2.imread( 'test.jpg')
img = cv2.imread( 'test.jpg', cv2.IMREAD_GRAYSCALE)
画像保存
※ この方法だと、実はアスキー以外のファイル名は扱えません。
下の方で詳しく記載します。
import cv2
cv2.imwrite( 'test.jpg', img,[cv2.IMWRITE_JPEG_QUALITY, 50])
cv2.imwrite( 'test.jpg', img)
cv2.imwrite( 'test.png', img)
サンプル
import cv2
# 画像の読込
img = cv2.imread( 'test.png')
# 画像の保存
cv2.imwrite( 'test.jpg' ,img)
アスキーのエラー例
import cv2
cv2.imread('よみこみ.jpg') # 結果 → None
cv2.imwrite('てすと.jpg',img) # 結果 → 縺ヲ縺吶→.jpg
アスキーコード以外のファイル名エラー対策 cvplusを使う
アスキーコード意外のファイル名対策にcvplusを使う方法があります。
from cvplus import cvt
img = cvt.imread('よみこみ.jpg')
cvt.imwrite('てすと.jpg',img)
簡単にインストールできます。
環境に合わせて使ってください。
py -m pip install cvplus
python -m pip install cvplus
python3 -m pip install cvplus
Githubにてマニュアル見れます。
https://github.com/daizyu/cvplus
アスキーコード以外のファイル名エラー対策:関数を自分で定義
自前で関数を書くことでも対応可能です。
import cv2
def imread(
filepath: str, flags: int = cv2.IMREAD_COLOR, dtype: type = np.uint8
) -> cv2.Mat:
"""
Read image file ( enable contains non-ascill code file and directory name )
Parameters
----------
filepath : str
File Name ( enable contains non-ascill code file and directory name )
flags : int
color mode
dtype : Array type
Returns
-------
image : cv2.Mat
CV2 Image ( Null : Error )
"""
try:
n: np.ndarray = np.fromfile(filepath, dtype)
img = cv2.imdecode(n, flags)
except Exception as e:
print(e)
return None
return img
def imwrite(filepath: str, img: cv2.Mat) -> bool:
"""
Write image file ( enable contains non-ascill code file and directory name )
Parameters
----------
filepath : str
File Name ( enable contains non-ascill code file and directory name )
img : cv2.Mat
CV2 image
Returns
-------
result : bool
True >> Successful
False >> Error
"""
ret, ary = cv2.imencode(os.path.splitext(filepath)[1], img)
if not ret:
return False
ary.tofile(filepath)
return True
カラーと、グレースケールについて
読込時にグレースケールに変換可能です
第2引数に cv2.IMREAD_GRAYSCALE を入れることでカラー画像ファイルでもグレースケールとして読込めます。
import cv2
img = cv2.imread( 'test.png' , cv2.IMREAD_GRAYSCALE)
カラーとグレースケールのデータの違いについて
カラーと、グレースケールでは内部の形式が違います。
shapeを見ていただくと以下のように形式が違う事が判ります。
カラーの場合、R,G,Bそれぞれデータを持っていますが、
グレースケールでは、カラーの様にデータを3種類もつ必要がないためです。
カラー:(y,x,3)
グレースケール:(y,x)
import cv2
img = cv2.imread( 'test.png' , cv2.IMREAD_GRAYSCALE)
print(img.shape)
(480, 640)
import cv2
img = cv2.imread( 'test.png' )
print(img.shape)
(480, 640, 3)
関連
おすすめ記事
SEO対策として、セキュリティー対策ソフトでチェック
動画ファイルの読込 - OpenCV、Python徹底解説
スクレイピング - Python徹底解説
Django テンプレート 使用 #1
国土地理院 標高タイル テキスト版を使って、ディズニーシーのプロメテウス火山を可視化
プログラムは独学が良いか、スクールが良いか?【無償カウンセリング、無料体験あり】
Supponsered
外部サイト
↓プログラムを学んでみたい場合、学習コースなどもおすすめです!