Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.13 KB | None | 0 0
  1. import os
  2. import glob
  3. import cv2
  4. import numpy as np
  5.  
  6. SZ=20
  7.  
  8.  
  9. def deskew(img):
  10.     m = cv2.moments(img)
  11.     if abs(m['mu02']) < 1e-2:
  12.         return img.copy()
  13.     skew = m['mu11'] / m['mu02']
  14.     M = np.float32([[1, skew, -0.5 * SZ * skew], [0, 1, 0]])
  15.     img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
  16.     return img
  17.  
  18.  
  19. def get_hog():
  20.     winSize = (20, 20)
  21.     blockSize = (8, 8)
  22.     blockStride = (4, 4)
  23.     cellSize = (8, 8)
  24.     nbins = 9
  25.     derivAperture = 1
  26.     winSigma = -1.
  27.     histogramNormType = 0
  28.     L2HysThreshold = 0.2
  29.     gammaCorrection = 1
  30.     nlevels = 64
  31.     signedGradient = True
  32.  
  33.     hog = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, nbins, derivAperture, winSigma,
  34.                             histogramNormType, L2HysThreshold, gammaCorrection, nlevels, signedGradient)
  35.  
  36.     return hog
  37.     affine_flags = cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR
  38.  
  39.  
  40. def get_contour_precedence(contour, cols):
  41.     tolerance_factor = 10
  42.     origin = cv2.boundingRect(contour)
  43.     return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]
  44.  
  45.  
  46. hog = get_hog();
  47.  
  48. model = cv2.ml.SVM_load('model.yml')
  49. cv2.namedWindow("im", cv2.WINDOW_NORMAL)
  50. img = cv2.imread('1.jpg')
  51. x, y, w, h = cv2.selectROI("im", img, False, False)
  52. cropped = img[y:y+h, x:x+w]
  53. cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
  54. test_samples = []
  55.  
  56. ret, thresh = cv2.threshold(cropped, 180, 255, cv2.THRESH_BINARY_INV)
  57. canny = cv2.Canny(thresh, 150, 200, apertureSize=3)
  58. contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  59.  
  60. drawing = canny.copy()
  61. rect = canny.copy()
  62. drawing = cv2.cvtColor(drawing, cv2.COLOR_GRAY2BGR)
  63. rect = cv2.cvtColor(rect, cv2.COLOR_GRAY2BGR)
  64. cv2.drawContours(drawing, contours, -1, (0, 255, 0))
  65. cv2.imshow("a", drawing)
  66. cv2.waitKey(0)
  67. contours.sort(key=lambda x:get_contour_precedence(x, thresh.shape[1]))
  68. first_x, _, first_w, _ = cv2.boundingRect(contours[0])
  69. last_x = first_x + first_w
  70. batch_test_samples = []
  71. for cnt in contours:
  72.     area = cv2.contourArea(cnt)
  73.     # print(cv2.contourArea(cnt))
  74.     if area > 10:
  75.         [x,y,w,h] = cv2.boundingRect(cnt)
  76.         # print(h)
  77.         if 5 < h < 25:
  78.             roi = cropped[y:y+h, x:x+w]
  79.             row, col = roi.shape[:2]
  80.             bottom = roi[row - 2:row, 0:col]
  81.             bordersize = 5
  82.             border = cv2.copyMakeBorder(roi, top=bordersize, bottom=bordersize, left=bordersize, right=bordersize,
  83.                                         borderType=cv2.BORDER_CONSTANT, value=[255,255,255])
  84.             roiresize = cv2.resize(border, (SZ, SZ), interpolation=cv2.INTER_AREA)
  85.             # cv2.imshow("roi", roiresize)
  86.             # cv2.waitKey(0)
  87.             if x - last_x < 10:
  88.                 batch_test_samples.append(roiresize)
  89.             else:
  90.                 batch_hog_descriptors = []
  91.                 for img in np.array(batch_test_samples).reshape(-1, 20, 20):
  92.                     batch_hog_descriptors.append(hog.compute(img))
  93.                 batch_hog_descriptors = np.squeeze(batch_hog_descriptors)
  94.                 test_samples.append(batch_hog_descriptors)
  95.                 batch_test_samples = [roiresize]
  96.             last_x = x + w
  97.             cv2.rectangle(rect, (x, y), (x + w, y + h), (0, 255, 0))
  98.  
  99. cv2.imshow("c", rect)
  100. cv2.waitKey(0)
  101. # resized = cv2.resize(cropped, (20, 20), interpolation=cv2.INTER_AREA)
  102. # gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
  103.  
  104. # test_samples = np.array(test_samples)
  105. # test_samples = test_samples.reshape(-1, SZ, SZ)
  106.  
  107. # print('Deskew images ... ')
  108. # deskewed = list(map(deskew, test_samples))
  109.  
  110. # t1 = cv2.getTickCount()
  111. # print('Defining HoG parameters ...')
  112. # HoG feature descriptor
  113.  
  114. # print('Calculating HoG descriptor for every image ... ')
  115. # hog_descriptors = []
  116. # for img in deskewed:
  117. #     hog_descriptors.append(hog.compute(img))
  118. # hog_descriptors = np.squeeze(hog_descriptors)
  119. # hog_descriptors = np.array(hog_descriptors)
  120. for batch in test_samples:
  121.     print(batch.shape)
  122.     print(model.predict(batch)[1].ravel())
  123.  
  124. # t2 = cv2.getTickCount()
  125. # print((t2 - t1)/cv2.getTickFrequency())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement