| commit | author | age | ||
| e555c0 | 1 | from pyzbar.pyzbar import decode |
| 02e0f7 | 2 | from sid_process import getSID |
| e555c0 | 3 | import cv2 |
| SP | 4 | import numpy as np |
| 5 | import math | |
| 6 | ||
| 7 | ||
| 511c2e | 8 | class Paper: |
| 762a5e | 9 | def __init__(self, filename=None, sid_classifier=None, settings=None): |
| 511c2e | 10 | self.filename = filename |
| SP | 11 | self.invalid = None |
| 12 | self.QRData = None | |
| 0436f6 | 13 | self.settings={'answer_treshold':0.25,} if settings is None else settings |
| 511c2e | 14 | self.errors = [] |
| SP | 15 | self.warnings = [] |
| 0436f6 | 16 | self.sid=None |
| 762a5e | 17 | self.sid_classifier = sid_classifier |
| 511c2e | 18 | if filename is not None: |
| SP | 19 | self.loadImage(filename) |
| 20 | self.runOcr() | |
| e555c0 | 21 | |
| 511c2e | 22 | def loadImage(self, filename, rgbchannel=0): |
| SP | 23 | self.img = cv2.imread(filename, rgbchannel) |
| 24 | if self.img is None: | |
| 25 | self.errors.append("File could not be loaded!") | |
| 26 | self.invalid = True | |
| 27 | return | |
| 28 | self.imgHeight, self.imgWidth = self.img.shape[0:2] | |
| e555c0 | 29 | |
| 511c2e | 30 | def saveImage(self, filename="debug_image.png"): |
| SP | 31 | cv2.imwrite(filename, self.img) |
| e555c0 | 32 | |
| 511c2e | 33 | def runOcr(self): |
| SP | 34 | if self.invalid == True: |
| 35 | return | |
| 36 | self.decodeQRandRotate() | |
| 37 | self.imgTreshold() | |
| 38 | skewAngle = 0 | |
| 39 | # try: | |
| 40 | # skewAngle=self.getSkewAngle() | |
| 41 | # except: | |
| 42 | # self.errors.append("Could not determine skew angle!") | |
| 43 | # self.rotateAngle(skewAngle) | |
| e555c0 | 44 | |
| 511c2e | 45 | self.generateAnswerMatrix() |
| e555c0 | 46 | |
| 511c2e | 47 | self.saveImage() |
| e555c0 | 48 | |
| 511c2e | 49 | def decodeQRandRotate(self): |
| SP | 50 | if self.invalid == True: |
| 51 | return | |
| 52 | blur = cv2.blur(self.img, (3, 3)) | |
| 53 | d = decode(blur) | |
| 54 | self.img = blur | |
| 55 | if len(d) == 0: | |
| 56 | self.errors.append("QR code could not be found!") | |
| 57 | self.data = None | |
| 58 | self.invalid = True | |
| 59 | return | |
| 60 | self.QRDecode = d | |
| 61 | self.QRData = d[0].data | |
| 62 | xpos = d[0].rect.left | |
| 63 | ypos = d[0].rect.top | |
| 64 | # check if image is rotated wrongly | |
| 65 | if xpos > self.imgHeight / 2.0 and ypost > self.imgWidth / 2.0: | |
| 66 | self.rotateAngle(180) | |
| e555c0 | 67 | |
| 511c2e | 68 | def rotateAngle(self, angle=0): |
| SP | 69 | rot_mat = cv2.getRotationMatrix2D( |
| 70 | (self.imgHeight / 2, self.imgWidth / 2), angle, 1.0 | |
| 71 | ) | |
| 72 | result = cv2.warpAffine( | |
| 73 | self.img, | |
| 74 | rot_mat, | |
| 75 | (self.imgHeight, self.imgWidth), | |
| 76 | flags=cv2.INTER_CUBIC, | |
| 77 | borderMode=cv2.BORDER_CONSTANT, | |
| 78 | borderValue=(255, 255, 255), | |
| 79 | ) | |
| e555c0 | 80 | |
| 511c2e | 81 | self.img = result |
| SP | 82 | self.imgHeight, self.imgWidth = self.img.shape[0:2] |
| e555c0 | 83 | |
| 511c2e | 84 | # todo, make better tresholding |
| e555c0 | 85 | |
| 511c2e | 86 | def imgTreshold(self): |
| SP | 87 | (self.thresh, self.bwimg) = cv2.threshold( |
| 88 | self.img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU | |
| 89 | ) | |
| e555c0 | 90 | |
| 511c2e | 91 | def getSkewAngle(self): |
| SP | 92 | neg = 255 - self.bwimg # get negative image |
| 93 | cv2.imwrite("debug_1.png", neg) | |
| e555c0 | 94 | |
| 511c2e | 95 | angle_counter = 0 # number of angles |
| SP | 96 | angle = 0.0 # collects sum of angles |
| 97 | cimg = cv2.cvtColor(self.img, cv2.COLOR_GRAY2BGR) | |
| e555c0 | 98 | |
| 511c2e | 99 | # get all the Hough lines |
| SP | 100 | for line in cv2.HoughLinesP(neg, 1, np.pi / 180, 325): |
| 101 | x1, y1, x2, y2 = line[0] | |
| 102 | cv2.line(cimg, (x1, y1), (x2, y2), (0, 0, 255), 2) | |
| 103 | # calculate the angle (in radians) | |
| 104 | this_angle = np.arctan2(y2 - y1, x2 - x1) | |
| 105 | if this_angle and abs(this_angle) <= 10: | |
| 106 | # filtered zero degree and outliers | |
| 107 | angle += this_angle | |
| 108 | angle_counter += 1 | |
| e555c0 | 109 | |
| 511c2e | 110 | # the skew is calculated of the mean of the total angles, #try block helps with division by zero. |
| SP | 111 | try: |
| 112 | skew = np.rad2deg( | |
| 113 | angle / angle_counter | |
| 114 | ) # the 1.2 factor is just experimental.... | |
| 115 | except: | |
| 116 | skew = 0 | |
| e555c0 | 117 | |
| 511c2e | 118 | cv2.imwrite("debug_2.png", cimg) |
| SP | 119 | return skew |
| e555c0 | 120 | |
| 511c2e | 121 | def locateUpMarkers(self, threshold=0.85, height=200): |
| SP | 122 | template = cv2.imread("template.png", 0) |
| 123 | w, h = template.shape[::-1] | |
| 124 | crop_img = self.img[0:height, :] | |
| 125 | res = cv2.matchTemplate(crop_img, template, cv2.TM_CCOEFF_NORMED) | |
| 126 | loc = np.where(res >= threshold) | |
| 127 | cimg = cv2.cvtColor(crop_img, cv2.COLOR_GRAY2BGR) | |
| 128 | # remove false matching of the squares in qr code | |
| 129 | loc_filtered_x = [] | |
| 130 | loc_filtered_y = [] | |
| 131 | if len(loc[0]) == 0: | |
| 132 | min_y = -1 | |
| 133 | else: | |
| 134 | min_y = np.min(loc[0]) | |
| 135 | for pt in zip(*loc[::-1]): | |
| 136 | if pt[1] < min_y + 20: | |
| 137 | loc_filtered_y.append(pt[1]) | |
| 138 | loc_filtered_x.append(pt[0]) | |
| 139 | # order by x coordinate | |
| 140 | loc_filtered_x, loc_filtered_y = zip( | |
| 141 | *sorted(zip(loc_filtered_x, loc_filtered_y)) | |
| 142 | ) | |
| 02e0f7 | 143 | # loc=[loc_filtered_y,loc_filtered_x] |
| SP | 144 | # remove duplicates |
| 511c2e | 145 | a = np.diff(loc_filtered_x) > 40 |
| SP | 146 | a = np.append(a, True) |
| 147 | loc_filtered_x = np.array(loc_filtered_x) | |
| 148 | loc_filtered_y = np.array(loc_filtered_y) | |
| 149 | loc = [loc_filtered_y[a], loc_filtered_x[a]] | |
| 150 | for pt in zip(*loc[::-1]): | |
| 151 | cv2.rectangle(cimg, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2) | |
| e555c0 | 152 | |
| 511c2e | 153 | cv2.imwrite("debug_3.png", cimg) |
| e555c0 | 154 | |
| 511c2e | 155 | self.xMarkerLocations = loc |
| SP | 156 | return loc |
| e555c0 | 157 | |
| 511c2e | 158 | def locateRightMarkers(self, threshold=0.85, width=200): |
| SP | 159 | template = cv2.imread("template.png", 0) |
| 160 | w, h = template.shape[::-1] | |
| 161 | crop_img = self.img[:, -width:] | |
| 162 | res = cv2.matchTemplate(crop_img, template, cv2.TM_CCOEFF_NORMED) | |
| 163 | loc = np.where(res >= threshold) | |
| 164 | cimg = cv2.cvtColor(crop_img, cv2.COLOR_GRAY2BGR) | |
| 165 | # remove false matching of the squares in qr code | |
| 166 | loc_filtered_x = [] | |
| 167 | loc_filtered_y = [] | |
| 168 | if len(loc[1]) == 0: | |
| 169 | min_x = -1 | |
| 170 | else: | |
| 171 | max_x = np.max(loc[1]) | |
| 172 | for pt in zip(*loc[::-1]): | |
| 173 | if pt[1] > max_x - 20: | |
| 174 | loc_filtered_y.append(pt[1]) | |
| 175 | loc_filtered_x.append(pt[0]) | |
| 176 | # order by y coordinate | |
| 177 | loc_filtered_y, loc_filtered_x = zip( | |
| 178 | *sorted(zip(loc_filtered_y, loc_filtered_x)) | |
| 179 | ) | |
| 180 | # loc=[loc_filtered_y,loc_filtered_x] | |
| 181 | # remove duplicates | |
| 182 | a = np.diff(loc_filtered_y) > 40 | |
| 183 | a = np.append(a, True) | |
| 184 | loc_filtered_x = np.array(loc_filtered_x) | |
| 185 | loc_filtered_y = np.array(loc_filtered_y) | |
| 186 | loc = [loc_filtered_y[a], loc_filtered_x[a]] | |
| 187 | for pt in zip(*loc[::-1]): | |
| 188 | cv2.rectangle(cimg, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2) | |
| e555c0 | 189 | |
| 511c2e | 190 | cv2.imwrite("debug_4.png", cimg) |
| e555c0 | 191 | |
| 511c2e | 192 | self.yMarkerLocations = [loc[0], loc[1] + self.imgWidth - width] |
| SP | 193 | return self.yMarkerLocations |
| e555c0 | 194 | |
| 511c2e | 195 | def generateAnswerMatrix(self): |
| SP | 196 | self.locateUpMarkers() |
| 197 | self.locateRightMarkers() | |
| e555c0 | 198 | |
| 511c2e | 199 | roixoff = 10 |
| SP | 200 | roiyoff = 5 |
| 201 | roiwidth = 50 | |
| 202 | roiheight = roiwidth | |
| 203 | totpx = roiwidth * roiheight | |
| e555c0 | 204 | |
| 511c2e | 205 | self.answerMatrix = [] |
| SP | 206 | for y in self.yMarkerLocations[0]: |
| 207 | oneline = [] | |
| 208 | for x in self.xMarkerLocations[1]: | |
| 209 | roi = self.bwimg[ | |
| 210 | y - roiyoff : y + int(roiheight - roiyoff), | |
| 211 | x - roixoff : x + int(roiwidth - roixoff), | |
| 212 | ] | |
| 213 | # cv2.imwrite('ans_x'+str(x)+'_y_'+str(y)+'.png',roi) | |
| 214 | black = totpx - cv2.countNonZero(roi) | |
| 215 | oneline.append(black / totpx) | |
| 216 | self.answerMatrix.append(oneline) | |
| 9efc18 | 217 | |
| SP | 218 | def get_enhanced_sid(self): |
| 02e0f7 | 219 | if self.sid_classifier is None: |
| SP | 220 | return "x" |
| 762a5e | 221 | if self.settings is not None: |
| SP | 222 | sid_mask=self.settings.get("sid_mask", None) |
| 5cb7c1 | 223 | es,err,warn = getSID( |
| 02e0f7 | 224 | self.img[ |
| SP | 225 | int(0.045 * self.imgHeight) : int(0.085 * self.imgHeight), |
| 226 | int(0.7 * self.imgWidth) : int(0.99 * self.imgWidth), | |
| 227 | ], | |
| 228 | self.sid_classifier, | |
| 762a5e | 229 | sid_mask |
| 02e0f7 | 230 | ) |
| 5cb7c1 | 231 | [self.errors.append(e) for e in err] |
| SP | 232 | [self.warnings.append(w) for w in warn] |
| 02e0f7 | 233 | return es |
| 0436f6 | 234 | |
| SP | 235 | |
| 236 | def get_code_data(self): | |
| 237 | qrdata = bytes.decode(self.QRData, 'utf8') | |
| 238 | if self.QRDecode[0].type=='EAN13': | |
| 239 | return {'exam_id': int(qrdata[0:7]), | |
| 240 | 'page_no': int(qrdata[7]), | |
| 241 | 'paper_id': int(qrdata[-5:-1]), | |
| 242 | 'faculty_id': None, | |
| 243 | 'sid': None | |
| 244 | } | |
| 245 | else: | |
| 246 | data=qrdata.split(',') | |
| 247 | retval={'exam_id': int(data[1]), | |
| 248 | 'page_no': int(data[3]), | |
| 249 | 'paper_id':int(data[2]), | |
| 250 | 'faculty_id':int(data[0]), | |
| 251 | } | |
| 252 | if(len(data)>4): | |
| 253 | retval['sid']=data[4] | |
| 254 | ||
| 255 | return retval | |
| 256 | ||
| 257 | def get_paper_ocr_data(self): | |
| 258 | data=self.get_code_data() | |
| 259 | data['qr']=self.QRData | |
| 260 | data['errors']=self.errors | |
| 261 | data['warnings']=self.warnings | |
| 262 | data['up_position']=(list(self.xMarkerLocations[1]/self.imgWidth), list(self.yMarkerLocations[1]/self.imgHeight)) | |
| 263 | data['right_position']=(list(self.xMarkerLocations[1]/self.imgWidth), list(self.yMarkerLocations[1]/self.imgHeight)) | |
| 264 | data['ans_matrix']=((np.array(self.answerMatrix)>self.settings['answer_treshold'])*1).tolist() | |
| 265 | if data['sid'] is None: | |
| 266 | data['sid']=self.get_enhanced_sid() | |
| 267 | return data | |