Guest User

Untitled

a guest
Oct 18th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. import sys
  2. import cv2
  3. import numpy as np
  4.  
  5. ####### training part ###############
  6. samples = np.loadtxt('generalsamples.data',np.float32)
  7. responses = np.loadtxt('generalresponses.data',np.float32)
  8. responses = responses.reshape((responses.size,1))
  9.  
  10. model = cv2.KNearest()
  11. model.train(samples,responses)
  12.  
  13. ############################# testing part #########################
  14.  
  15. im = cv2.imread('pi.png')
  16. out = np.zeros(im.shape,np.uint8)
  17. gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
  18. thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
  19.  
  20. contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
  21.  
  22. for cnt in contours:
  23. if cv2.contourArea(cnt)>50:
  24. [x,y,w,h] = cv2.boundingRect(cnt)
  25. if h>28:
  26. cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
  27. roi = thresh[y:y+h,x:x+w]
  28. roismall = cv2.resize(roi,(10,10))
  29. roismall = roismall.reshape((1,100))
  30. roismall = np.float32(roismall)
  31. retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
  32. string = str(int((results[0][0])))
  33. cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
  34.  
  35. cv2.imshow('im',im)
  36. cv2.imshow('out',out)
  37. cv2.waitKey(0)
  38.  
  39. im = cv2.imread('/home/kris/Рабочий стол/IwQY6.png')
  40. im3 = im.copy()
  41.  
  42. gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
  43. blur = cv2.GaussianBlur(gray,(5,5),0)
  44. thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
  45.  
  46. ################# Now finding Contours ###################
  47.  
  48. _, contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
  49.  
  50. samples = np.empty((0,100))
  51. responses = []
  52. keys = [i for i in range(48,58)]
  53.  
  54. for cnt in contours:
  55. if cv2.contourArea(cnt)>50:
  56. [x,y,w,h] = cv2.boundingRect(cnt)
  57.  
  58. if h>28:
  59. cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
  60. roi = thresh[y:y+h,x:x+w]
  61. roismall = cv2.resize(roi,(10,10))
  62. cv2.imshow('norm',im)
  63. key = cv2.waitKey(0)
  64.  
  65. if key == 27: # (escape to quit)
  66. sys.exit()
  67. elif key in keys:
  68. responses.append(int(chr(key)))
  69. sample = roismall.reshape((1,100))
  70. samples = np.append(samples,sample,0)
  71.  
  72. responses = np.array(responses,np.float32)
  73. responses = responses.reshape((responses.size,1))
  74. print("training complete")
  75.  
  76. np.savetxt('generalsamples.data',samples)
  77. np.savetxt('generalresponses.data',responses)
Add Comment
Please, Sign In to add comment