Python3 OpenCV3でK-Means法による減色処理
減色処理は、写真を油絵やイラストのように変換したいときに使われる。
[amazonjs asin="4839952965″ locale="JP" title="OpenCV 3 プログラミングブック"]
前提
元画像
カラス(karasu.jpg) をsource/imageディレクトリに設置する。
減色処理
sourceディレクトリにk_means.pyを作成する。
[python title="k_means.pyの内容"]
import numpy as np
import cv2
if __name__ == '__main__’:
img_src = cv2.imread('./image/karasu.jpg’)
Z = img_src.reshape((-1,3))
# float32に変換
Z = np.float32(Z)
# K-Means法
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 4
ret,label,center=cv2.kmeans(Z,
K,
None,
criteria,
10,
cv2.KMEANS_RANDOM_CENTERS)
# UINT8に変換
center = np.uint8(center)
res = center[label.flatten()]
img_dst = res.reshape((img_src.shape))
cv2.imshow('Quantization’, img_dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
[/python]
実行してみる。
[python]
(opencv_python) $ python k_means.py
[/python]
イラストのようなタッチになった。
Kの値を4から8に変えてみた。
少し元の画像に近づいた。
ディスカッション
コメント一覧
まだ、コメントがありません