10-7FindLines_1.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: img = cv2.imread(‘IMG_1239.JPG’)
005:
006: img = getResize(img)
007:
008: gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
009: ret, bw = cv2.threshold(src=gray, thresh=0, maxval=255, type=cv2.THRESH_OTSU)
010: bw = cv2.Canny(bw, 10, 200, apertureSize=3)
011: # 入力画像,距離分解能,角度分解能,閾値
012: lines = cv2.HoughLines(image=bw, rho=1, theta=np.pi/180, threshold=300)
013:
014: if lines is not None:
015: for rho, theta in lines[:, 0]:
016: a = np.cos(theta)
017: b = np.sin(theta)
018: x0 = a * rho
019: y0 = b * rho
020:
021: x1 = int(x0 + 1000 * (-b))
022: y1 = int(y0 + 1000 * a)
023: x2 = int(x0 – 1000 * (-b))
024: y2 = int(y0 – 1000 * a)
025: cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
026:
027: cv2.imshow(‘Edges’, bw)
028: cv2.imshow(‘Final result’, img)
029: cv2.waitKey(0)
030:
031: def getResize(src):
032: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
033: height = src.shape[0]
034: width = src.shape[1]
035:
036: largeSize = max(height, width) # 大きい方の辺のサイズ
037: resizeRate = basePixSize / largeSize # 変更比率を計算
038: shotSize = min(height, width) * resizeRate
039: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
040:
041: return dst
042:
043: if __name__ == ‘__main__’:
044: print(cv2.__version__)
045:
046: __main()