Advertisement
larsupilami73

Hough transform animation

Nov 27th, 2019
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.82 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # Straightforward instructional implementation of Hough transform: how to find lines in an image?
  3. # The image is tranformed to Hough space.
  4. # The maxima in Hough space coincide with angles and perpendicular distances of straight lines in
  5. # the input image origin (top left here).
  6. # See: https://en.wikipedia.org/wiki/Hough_transform
  7. # The smart and fast way to do this would be with opencv:
  8. # https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
  9. # larsupilami73
  10.  
  11. import os
  12. from scipy import *
  13. import matplotlib.pyplot as plt
  14.  
  15. N = 100 #100x100 image size
  16.  
  17.  
  18. #make straight line in an array
  19. def StraightLine(X,m,c):
  20.     if abs(m)<=1:
  21.         for n in range(X.shape[0]):
  22.             k = round(n*m + c)
  23.             if (k<N) and (k>=0): A[int(k),n] = 1.0
  24.     else: # to avoid lines with gaps
  25.         for n in range(X.shape[0]):
  26.             k = round((n-c)/m)
  27.             if (k<N) and (k>=0): A[n,int(k)] = 1.0
  28.  
  29. #the Hough transform
  30. #for simplicity, keep the Hough space same dimensions as the input image
  31. #assuming square image
  32. def HoughTransform(X, threshold=0.5):
  33.     D = X.shape[0]
  34.     H = zeros((D,D))
  35.     points=where(X>threshold)
  36.     pxs = points[1] # watch out!
  37.     pys = points[0]
  38.     for px,py in zip(pxs,pys):
  39.         for d in range(D):
  40.             tetha = pi*d/D
  41.             rho = round(px*cos(tetha) + py*sin(tetha)) #see: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html      
  42.             if rho<D and rho>=0:
  43.                 H[int(rho),d] +=1.0 #row=distance,column=angle
  44.             #print(px,py,d,rho)
  45.    
  46.     H /=H.max() #normalize [0..1]
  47.     return H
  48.    
  49.  
  50. #temp directory for the frames
  51. if not os.path.exists('./frames'):
  52.     os.mkdir('./frames')
  53. try:
  54.     os.system('rm ./frames/frame*.png')
  55. except:
  56.     pass
  57.  
  58. #make straight lines, y=mx+c
  59. MC = []
  60. for c in range(10,90,5): MC.append((0,c))
  61. for c in range(90,50,-5): MC.append((0,c))
  62. for m in linspace(0,5,25): MC.append((m,50))
  63. for m in linspace(5,-2,50): MC.append((m,50))
  64. for c in range(50,200,5): MC.append((-2,c))
  65. for k in range(10): MC.append((-2,200))
  66.  
  67. fig, (ax1,ax2) = plt.subplots(1,2, sharey=False,figsize=(6.4,3.2), dpi=150)
  68. plt.subplots_adjust(wspace=0.4)
  69. for k,(m,c) in enumerate(MC):
  70.     #make the input image
  71.     A =  zeros((N,N))
  72.     StraightLine(A,m,c)
  73.     #do the transform
  74.     HA = HoughTransform(A)
  75.  
  76.     #make the input image
  77.     ax1.imshow(A,cmap=plt.cm.gray)
  78.     ax1.set_title(r'Input image: $y=mx+c$')
  79.     ax1.set_xlabel('x')
  80.     ax1.set_ylabel('y')
  81.     ax1.set_xticks([0,25,50,75,100])
  82.     ax1.set_yticks([0,25,50,75,100])
  83.     ax1.text(1,97,r'$m=%.1f$   $c=%.1f$' %(m,c), color='lightgreen')
  84.  
  85.     #make the Hough space image
  86.     ax2.imshow(pow(HA,0.65),cmap=plt.cm.afmhot) # x^(1/a) >= x in ]0,1] for a>1, so makes pixels clearer in Hough space
  87.     ax2.set_title(r'Hough space: $(d,\theta)$')
  88.     ax2.set_ylabel('Perp. dist. to origin [pixels]')
  89.     ax2.set_xlabel('Angle [degrees]')
  90.     ax2.set_xlim(0,N)
  91.    
  92.     #show where the maximum is (for only one line)
  93.     #for more lines, we would select several local maxima in Hough space
  94.     ym,xm = where(HA==HA.max())
  95.     ym = ym[0]
  96.     xm= xm[0]
  97.    
  98.     ax2.scatter([xm],[ym],s=100,facecolors='none',marker='o',alpha=0.6,linewidths=1.5,edgecolors='lightgreen')
  99.    
  100.     #add angle/distance text
  101.     ax2.text(1,97,r'$d=%.1f$   $\theta=%.1f ^{\circ}$' %(ym,180*xm/N), color='lightgreen')
  102.    
  103.     xt = [x for x in linspace(0.,N,5)]
  104.     ax2.set_xticks(xt)
  105.     ax2.set_xticklabels(['%.1f'%(180*x/N) for x in xt]) #position to angle
  106.     ax2.set_yticks([0,25,50,75,100])
  107.  
  108.     #plt.tight_layout()
  109.     plt.savefig('./frames/frame%05d.png' %k)
  110.     ax1.clear()
  111.     ax2.clear()
  112.     print('Frame number: %d/%d' %(k+1,len(MC)))
  113.  
  114.  
  115. #now assemble all the pictures in a movie
  116. #print('converting to gif!')
  117. #os.system('convert -delay 40 -loop 0 ./frames/*.png fb_tot.gif')
  118. #or to mp4
  119. print('converting to mp4!')
  120. os.system("ffmpeg -y -r 5 -i ./frames/frame%05d.png -c:v libx264 -vf fps=10 hough.mp4")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement