"""
@file hough_lines.py
@brief This program demonstrates line finding with the Hough transform
"""import sys
import math
import cv2 as cv
import numpy as np
defmain(argv):
default_file ='/Users/panhaokang/Documents/1.jpg'
filename = argv[0]iflen(argv)>0else default_file
# Loads an image
src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE)# Check if image is loaded fineif src isNone:print('Error opening image!')print('Usage: hough_lines.py [image_name -- default '+ default_file +'] \n')return-1
dst = cv.Canny(src,50,200,None,3)# Copy edges to the images that will display the results in BGR
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
cdstP = np.copy(cdst)
lines = cv.HoughLines(dst,1, np.pi /180,150,None,0,0)if lines isnotNone:for i inrange(0,len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 =(int(x0 +1000*(-b)),int(y0 +1000*(a)))
pt2 =(int(x0 -1000*(-b)),int(y0 -1000*(a)))
cv.line(cdst, pt1, pt2,(0,0,255),3, cv.LINE_AA)
linesP = cv.HoughLinesP(dst,1, np.pi /180,50,None,50,10)if linesP isnotNone:for i inrange(0,len(linesP)):
l = linesP[i][0]
cv.line(cdstP,(l[0], l[1]),(l[2], l[3]),(0,0,255),3, cv.LINE_AA)
cv.imshow("Source", src)
cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)
cv.waitKey()return0if __name__ =="__main__":
main(sys.argv[1:])
Radon
import numpy as np
import cv2
from skimage.transform import radon
filename ='your_filename'# Load file, converting to grayscale
img = cv2.imread(filename)
I = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = I.shape
# If the resolution is high, resize the image to reduce processing time.if(w >640):
I = cv2.resize(I,(640,int((h / w)*640)))
I = I - np.mean(I)# Demean; make the brightness extend above and below zero# Do the radon transform
sinogram = radon(I)# Find the RMS value of each row and find "busiest" rotation,# where the transform is lined up perfectly with the alternating dark# text and white lines
r = np.array([np.sqrt(np.mean(np.abs(line)**2))for line in sinogram.transpose()])
rotation = np.argmax(r)print('Rotation: {:.2f} degrees'.format(90- rotation))# Rotate and save with the original resolution
M = cv2.getRotationMatrix2D((w/2, h/2),90- rotation,1)
dst = cv2.warpAffine(img, M,(w, h))
cv2.imwrite('rotated.jpg', dst)
Hough"""@file hough_lines.py@brief This program demonstrates line finding with the Hough transform"""import sysimport mathimport cv2 as cvimport numpy as npdef main(argv): default_file = '/Users/panhaokang/Documents/1.jpg' filename =