10-7FindLines_1_gpu.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: global gpuImg
005: img = cv2.imread(‘IMG_1239.JPG’)
006:
007: gpuImg = getGpuResize(img)
008: img = gpuImg.download()
009:
010: gpuImg = cv2.cuda.cvtColor(src=gpuImg, code=cv2.COLOR_BGR2GRAY)
011: ret, gpuImg = cv2.cuda.threshold(src=gpuImg, thresh=180, maxval=255, type=cv2.THRESH_BINARY)
012:
013: cannyDetector = cv2.cuda.createCannyEdgeDetector(low_thresh=10, high_thresh=200, apperture_size=3)
014: gpuImg = cannyDetector.detect(gpuImg)
015: # 距離分解能,角度分解能,閾値
016: linesDetector = cv2.cuda.createHoughLinesDetector(rho=1, theta=np.pi/180, threshold=300)
017: cuLines = linesDetector.detect(gpuImg)
018: lines = cuLines.download()
019:
020: if lines is not None:
021: for line in lines:
022: rho, theta = line[0]
023: a = np.cos(theta)
024: b = np.sin(theta)
025: x0 = a * rho
026: y0 = b * rho
027:
028: x1 = int(x0 + 1000 * (-b))
029: y1 = int(y0 + 1000 * a)
030: x2 = int(x0 – 1000 * (-b))
031: y2 = int(y0 – 1000 * a)
032: cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
033:
034: cv2.imshow(‘Final result’, img)
035: cv2.waitKey(0)
036:
037: def getGpuResize(src):
038: global gpuImg
039: gpuImg.upload(src)
040:
041: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
042: height = src.shape[0]
043: width = src.shape[1]
044:
045: largeSize = max(height, width) # 大きい方の辺のサイズ
046: resizeRate = basePixSize / largeSize # 変更比率を計算
047: gpuImg = cv2.cuda.resize(gpuImg, (int(width * resizeRate), int(height * resizeRate)))
048:
049: return gpuImg
050:
051: if __name__ == ‘__main__’:
052: print(cv2.__version__)
053:
054: gpuImg = cv2.cuda_GpuMat()
055: __main()