cf. http://www-tlab.math.ryukoku.ac.jp/wiki/index.php?PIP%2F2017%2Fhw10omake
- version.py OpenCVとNumPyのバージョン確認
- displayimage.py 画像を反転して表示&出力
- kapiHough.py Hough変換
cf. http://www-tlab.math.ryukoku.ac.jp/wiki/index.php?PIP%2F2017%2Fhw10omake
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import cv2 | |
import numpy as np | |
# 画像を読み込む | |
img = cv2.imread( 'blackuni3.png' ) | |
# img の画素値を反転 ==> 左右を反転 | |
img2 = cv2.flip( 255 - img, 1 ) | |
# img2 を 'Hoge' という名前のウインドウに表示 | |
cv2.imshow( 'Hoge', img2 ) | |
# 上記のウィンドウを選択して何かキーを押すまで待つ | |
cv2.waitKey( 0 ) | |
# PNG形式の画像として保存する | |
cv2.imwrite( 'hoge.png', img2 ) |
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
from __future__ import division | |
import cv2 | |
import numpy as np | |
# 画像 img に lines に格納されたパラメータの直線を重ねて描く | |
# | |
def drawLines( img, lines ): | |
for x in lines: | |
rho, theta = x[0] | |
# (rho, theta) の直線を画像の端までで描く | |
if np.pi/4 <= theta and theta <= 3*np.pi/4: | |
val = rho / np.sin( theta ) | |
pt1 = ( 0, int( val ) ) | |
pt2 = ( width, int( val - width / np.tan( theta ) ) ) | |
else: | |
val = rho / np.cos( theta ) | |
pt1 = ( int( val ), 0 ) | |
pt2 = ( int( val - height * np.tan( theta ) ), height ) | |
print( rho, theta, pt1, pt2 ) | |
cv2.line( img, pt1, pt2, ( 0, 0, 255 ), thickness = 2 ) | |
if __name__ == "__main__": | |
# Canny法の二つのしきい値 th1, th2 を変えると抽出される特徴点が変わり Hough 変換の結果も変わる | |
# Hough変換のしきい値 threshold を変えると検出される直線の数が変わる | |
FnSrc = 'kapibara640x480.jpg' | |
# 画像を読み込む | |
imgColor = cv2.imread( FnSrc ) | |
height, width = imgColor.shape[0], imgColor.shape[1] | |
# グレイスケールに変換 | |
imgGray = cv2.cvtColor( imgColor, cv2.COLOR_BGR2GRAY ) | |
# Canny法でエッジを検出 | |
th1, th2 = 100, 400 # 2つのしきい値 | |
imgCanny = cv2.Canny( imgGray, th1, th2, apertureSize = 3 ) | |
# Hough変換 | |
rhoRes, thetaRes = 1, 1*np.pi/180 # (rho, theta)平面を分割する格子の間隔 | |
threshold = 120 # 票数のしきい値 | |
lines = cv2.HoughLines( imgCanny, rhoRes, thetaRes, threshold ) | |
print( '( number of detected lines ) = ', lines.shape[0] ) | |
# 元画像に検出した直線を重ねて描く | |
drawLines( imgColor, lines ) | |
# 画像を表示 | |
cv2.imshow( "imgCanny", imgCanny ) | |
cv2.imshow( "imgColor", imgColor ) | |
cv2.waitKey( 0 ) |
from __future__ import print_function | |
from __future__ import division | |
import cv2 | |
import numpy as np | |
print( 'version of OpenCV:', cv2.__version__ ) | |
print( 'version of NumPy:', np.__version__ ) |