Quantcast
Channel: 初心者タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 21085

目指せ画像処理マスター!画像処理100本ノックやったったPart6:Q12とQ20

$
0
0

今日はQ12とエッジ検出系の問題とばしてQ20をやっていきます

Q12:モーションフィルタ

疲れてきたので特に何も書きませんが最初フィルタのサイズミスってて全然処理かかってなくて戸惑いました。printしまくってなんとか原因究明。凡ミス恐ろしい

今回覚えたのはnp.diagです

importcv2importnumpyasnp#input
img=cv2.imread("imori.jpg")H,W,C=img.shapeprint(img.shape)#Filter
#kernel size
k=3K=np.diag([1]*k).astype(np.float)K/=k#K.shape (3,3)
#K = [[1/3,0,0],[0,1/3,0],[0,0,1/3]]
#zero pad 
out=np.zeros((H+2,W+2,C),dtype=np.float)out[1:1+H,1:1+W,:]=img.copy().astype(np.float)tmp=out.copy()#print(tmp)
#filtered
foryinrange(H):forxinrange(W):forcinrange(C):out[1+y,1+x,c]=np.sum(K*tmp[y:y+3,x:x+3,c])#remove zero pad 
out=out[1:1+H,1:1+H,:].astype(np.uint8)print(out)cv2.imwrite("anspic_q12.jpg",out)cv2.imshow("result",out)cv2.waitKey(0)cv2.destroyAllWindows()

Q20:ヒストグラム表示

今回の参考
https://pythondatascience.plavox.info/matplotlib/%E3%83%92%E3%82%B9%E3%83%88%E3%82%B0%E3%83%A9%E3%83%A0

これはできるぞ!と思ってやってみたらひっかかった

importcv2importnumpyasnpimportmatplotlib.pyplotasplt#input
img=cv2.imread("imori_dark.jpg").astype(np.float)plt.hist(img,bins=255,range=(0,255))plt.savefig("out.png")plt.show()

上みたいに書いたら怒られた

# python q20.py
Traceback (most recent call last):
  File "q20.py", line 8, in <module>
    plt.hist(img, bins=255, range=(0,255))
  File "/usr/local/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2610, in hist
    if data is not None else {}), **kwargs)
  File "/usr/local/lib/python3.7/site-packages/matplotlib/__init__.py", line 1543, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "/usr/local/lib/python3.7/site-packages/matplotlib/axes/_axes.py", line 6569, in hist
    x = cbook._reshape_2D(x, 'x')
  File "/usr/local/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 1386, in _reshape_2D
    raise ValueError("{} must have 2 or fewer dimensions".format(name))
ValueError: x must have 2 or fewer dimensions

データの配列が2次元以上になってるぞと怒られました。
1次元になるように変換
np.ravelを使います

参考
https://note.nkmk.me/python-numpy-ravel-flatten/

importcv2importnumpyasnpimportmatplotlib.pyplotasplt#input
img=cv2.imread("imori_dark.jpg").astype(np.float)plt.hist(img.ravel(),bins=255,range=(0,255))plt.savefig("out.png")plt.show()

描けた!
out.png

おわりに

やっぱりなんか表示できるのは嬉しい


Viewing all articles
Browse latest Browse all 21085

Trending Articles