ハフ変換(直線検出)

V2.4.11, V3.0.0
In [1]:
# -*- coding: utf-8 -*-
import cv2
import numpy as np

#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline

#画像読込
in_img = cv2.imread("building.jpg")

# 入力画像をグレースケール変換
gray = cv2.cvtColor(in_img,cv2.COLOR_BGR2GRAY)

#ガウシアンフィルタ処理
gauss = cv2.GaussianBlur(gray,(9,9),0)

#キャニーエッジ検出
edges = cv2.Canny(gauss,100,150)
                  
#ハフ変換                  
lines = cv2.HoughLines(edges,2,np.pi/180,200)

# グレースケール変換をBGR変換
color = cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)

# 直線の描画
for rho,theta in lines[0]:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))
        cv2.line(color,(x1,y1),(x2,y2),(0,0,255),2)

#OpenCVがBGRなのでRGBに変換
disp_in_img  = cv2.cvtColor(color,  cv2.COLOR_BGR2RGB)

#画像表示
plt.figure(figsize=(15,10))
plt.subplot(221)
plt.imshow(gray,cmap='gray', aspect='auto')
plt.subplot(222)
plt.imshow(edges,cmap='gray')
plt.subplot(223)
plt.imshow(disp_in_img)
Out[1]:
<matplotlib.image.AxesImage at 0x5884130>

inserted by FC2 system