├── CreditCardOcrWithOpencv.py ├── CreditCardOcrWithOpencv ├── modelCardNumberPicture │ ├── 0.jpg │ ├── 1.jpg │ ├── 10.jpg │ ├── 11.jpg │ ├── 12.jpg │ ├── 13.jpg │ ├── 15.jpg │ ├── 16.jpg │ ├── 17.jpg │ ├── 18.jpg │ ├── 19.jpg │ ├── 2.jpg │ ├── 20.jpg │ ├── 3.jpg │ ├── 4.jpg │ ├── 5.jpg │ ├── 6.jpg │ ├── 7.jpg │ ├── 8.jpg │ └── 9.jpg └── modelCardPicture │ ├── 0.jpg │ ├── 1.jpg │ ├── 10.jpg │ ├── 12.jpg │ ├── 13.jpg │ ├── 14.jpg │ ├── 15.jpg │ ├── 16.jpg │ ├── 17.jpg │ ├── 18.jpg │ ├── 2.jpg │ ├── 3.jpg │ ├── 4.jpg │ ├── 5.jpg │ ├── 6.jpg │ ├── 7.jpg │ ├── 8.jpg │ └── 9.jpg ├── LICENSE ├── README.md ├── augmentingPicture.py ├── demo └── demo.mp4 ├── neng.traineddata └── opencv-featureDetection /CreditCardOcrWithOpencv.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import pytesseract 4 | import tempfile 5 | from PIL import Image 6 | 7 | 8 | def convertingPintToTheFourDimensionalArray(pts): 9 | rect = [[0, 0], [0, 0], [0, 0], [0, 0]] 10 | rect[0][0] = (pts[0][0][0]) 11 | rect[0][1] = (pts[0][0][1]) 12 | 13 | rect[1][0] = (pts[1][0][0]) 14 | rect[1][1] = (pts[1][0][1]) 15 | 16 | rect[2][0] = (pts[2][0][0]) 17 | rect[2][1] = (pts[2][0][1]) 18 | 19 | rect[3][0] = (pts[3][0][0]) 20 | rect[3][1] = (pts[3][0][1]) 21 | return rect 22 | 23 | 24 | def order_points(pts): 25 | pts = convertingPintToTheFourDimensionalArray(pts) 26 | rect = np.zeros((4, 2), dtype="float32") 27 | for j in range(4): 28 | for i in range(4): 29 | if pts[i][0] >= pts[j][0]: 30 | pts[i], pts[j] = pts[j], pts[i] 31 | if pts[1][1] <= pts[0][1]: 32 | rect[0] = pts[1] 33 | rect[3] = pts[0] 34 | else: 35 | rect[0] = pts[0] 36 | rect[3] = pts[1] 37 | pts = np.delete(pts, 0, 0) 38 | pts = np.delete(pts, 0, 0) 39 | if pts[1][1] <= pts[0][1]: 40 | rect[1] = pts[1] 41 | rect[2] = pts[0] 42 | else: 43 | rect[1] = pts[0] 44 | rect[2] = pts[1] 45 | return rect 46 | 47 | def four_point_transform(image, pts): 48 | rect = order_points(pts) 49 | (tl, tr, br, bl) = rect 50 | widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) 51 | widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) 52 | maxWidth = max(int(widthA), int(widthB)) 53 | heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) 54 | heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) 55 | maxHeight = max(int(heightA), int(heightB)) 56 | dst = np.array([ 57 | [0, 0], 58 | [maxWidth - 1, 0], 59 | [maxWidth - 1, maxHeight - 1], 60 | [0, maxHeight - 1]], dtype = "float32") 61 | M = cv2.getPerspectiveTransform(rect, dst) 62 | warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight)) 63 | return warped 64 | 65 | def findingTotalCard(testingPath,modelPath): 66 | numberOfModelCard = 22 67 | testImage = cv2.imread(testingPath) 68 | testImage = cv2.resize(testImage,(800,600)) 69 | cv2.imshow("original image", testImage) 70 | cv2.waitKey(0) 71 | testingImage = cv2.imread(testingPath) 72 | for i in range(numberOfModelCard): 73 | x , image = findingCardPosition(testingPath,modelPath+str(i)+".jpg") 74 | if x==1: 75 | cardImage = image 76 | return cardImage 77 | 78 | def findingTotalCardNumber(testingImage,modelPath): 79 | find =0 80 | cardImage = testingImage 81 | numberOfCardNumberPicture=18 82 | imager=cv2.imread(modelPath+str(0)+".jpg") 83 | for i in range(numberOfCardNumberPicture): 84 | x,image = findingCardNumbersPosition(testingImage,modelPath+str(i)+".jpg") 85 | if x == 1: 86 | find=1 87 | cardImage = image 88 | break 89 | return cardImage,find 90 | def findingCardPosition(testingPath,modelPath): 91 | testingImage = cv2.imread(testingPath) 92 | img = cv2.imread(modelPath, cv2.IMREAD_GRAYSCALE) # queryiamge 93 | sift = cv2.xfeatures2d.SIFT_create() 94 | kp_image, desc_image = sift.detectAndCompute(img, None) 95 | 96 | index_params = dict(algorithm=0, trees=5) 97 | search_params = dict() 98 | flann = cv2.FlannBasedMatcher(index_params, search_params) 99 | frame = testingImage 100 | 101 | grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # trainimage 102 | kp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) 103 | matches = flann.knnMatch(desc_image, desc_grayframe, k=2) 104 | good_points = [] 105 | for m, n in matches: 106 | if m.distance < 0.5 * n.distance: 107 | good_points.append(m) 108 | 109 | # Homography 110 | if len(good_points) > 12: 111 | query_pts = np.float32([kp_image[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2) 112 | train_pts = np.float32([kp_grayframe[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2) 113 | matrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) 114 | matches_mask = mask.ravel().tolist() 115 | h, w = img.shape 116 | pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2) 117 | dst = cv2.perspectiveTransform(pts, matrix) 118 | homography = cv2.polylines(frame, [np.int32(dst)], True, (0, 0, 255), 1) 119 | croped_image = four_point_transform(frame,np.int32(dst)) 120 | cv2.destroyAllWindows() 121 | return 1,croped_image 122 | else: 123 | print("can't find card position") 124 | return 2,frame 125 | cv2.destroyAllWindows() 126 | def findingCardNumbersPosition(testingImage,modelPath): 127 | img = cv2.imread(modelPath, cv2.IMREAD_GRAYSCALE) # queryiamge 128 | # Features 129 | sift = cv2.xfeatures2d.SIFT_create() 130 | kp_image, desc_image = sift.detectAndCompute(img, None) 131 | # Feature matching 132 | index_params = dict(algorithm=0, trees=5) 133 | search_params = dict() 134 | flann = cv2.FlannBasedMatcher(index_params, search_params) 135 | frame = testingImage 136 | grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # trainimage 137 | kp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) 138 | matches = flann.knnMatch(desc_image, desc_grayframe, k=2) 139 | good_points = [] 140 | for m, n in matches: 141 | if m.distance < 0.5 * n.distance: 142 | good_points.append(m) 143 | 144 | if len(good_points) > 10: 145 | query_pts = np.float32([kp_image[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2) 146 | train_pts = np.float32([kp_grayframe[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2) 147 | matrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) 148 | matches_mask = mask.ravel().tolist() 149 | 150 | h, w = img.shape 151 | pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2) 152 | dst = cv2.perspectiveTransform(pts, matrix) 153 | hq, wq, e = frame.shape 154 | croped_image = four_point_transform(frame,np.int32(dst)) 155 | cv2.destroyAllWindows() 156 | return 1, croped_image 157 | else: 158 | print("can't find card number position") 159 | return 2, frame 160 | cv2.destroyAllWindows() 161 | 162 | def process_image_for_ocr(file_path): 163 | # TODO : Implement using opencv 164 | temp_filename = set_image_dpi(file_path) 165 | im_new = remove_noise_and_smooth(temp_filename) 166 | im_new = clearNoise(im_new) 167 | return im_new 168 | 169 | def set_image_dpi(file_path): 170 | IMAGE_SIZE = 1800 171 | BINARY_THREHOLD = 180 172 | im = Image.open(file_path) 173 | length_x, width_y = im.size 174 | factor = max(1, int(IMAGE_SIZE / length_x)) 175 | size = factor * length_x, factor * width_y 176 | im_resized = im.resize(size, Image.ANTIALIAS) 177 | temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') 178 | temp_filename = temp_file.name 179 | im_resized.save(temp_filename, dpi=(300, 300)) 180 | return temp_filename 181 | 182 | def image_smoothening(img): 183 | BINARY_THREHOLD = 180 184 | ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) 185 | ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 186 | blur = cv2.GaussianBlur(th2, (1, 1), 0) 187 | ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 188 | return th3 189 | 190 | def remove_noise_and_smooth(file_name): 191 | img = cv2.imread(file_name, 0) 192 | filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 193 | 3) 194 | kernel = np.ones((1, 1), np.uint8) 195 | opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel) 196 | closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) 197 | img = image_smoothening(img) 198 | or_image = cv2.bitwise_or(img, closing) 199 | return or_image 200 | def clearNoise(image): 201 | kernel = np.ones((5,5),np.uint8) 202 | image = cv2.dilate(image,kernel,iterations = 1) 203 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 204 | for i in range(30): 205 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 206 | image = cv2.erode(image,kernel,iterations = 1) 207 | image = cv2.dilate(image,kernel,iterations = 1) 208 | image = cv2.dilate(image,kernel,iterations = 1) 209 | for i in range(100): 210 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 211 | image = cv2.erode(image,kernel,iterations = 1) 212 | image = cv2.erode(image,kernel,iterations = 1) 213 | return image 214 | 215 | def ocr(image): 216 | image = image 217 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 218 | cv2.imshow("Image", gray) 219 | 220 | gray = cv2.medianBlur(gray, 3) 221 | 222 | filename = "newImage.jpg" 223 | cv2.imwrite(filename, gray) 224 | 225 | text = pytesseract.image_to_string(Image.open(filename), lang='neng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') 226 | print(text) 227 | cv2.imshow("Output", gray) 228 | cv2.waitKey(0) 229 | return text 230 | 231 | 232 | font = cv2.FONT_HERSHEY_SIMPLEX 233 | org = (50, 50) 234 | fontScale = 2 235 | color = (0, 50, 255) 236 | thickness = 5 237 | modelCardPicturesFolderPath = "CreditCardOcrWithOpencv\\modelCardPicture\\" 238 | modelCardNumberPicturesFolderPath = "CreditCardOcrWithOpencv\\modelCardNumberPicture\\" 239 | testingImagePath = "type your path of image" 240 | try: 241 | images = findingTotalCard(testingImagePath,modelCardPicturesFolderPath) 242 | try: 243 | image,find = findingTotalCardNumber(images,modelCardNumberPicturesFolderPath) 244 | if find==1: 245 | w,h,c = image.shape 246 | image = cv2.resize(image, (int(h/2), int(w/2))) 247 | path = "testing picture\\newImage.jpg" 248 | cardNumber = pytesseract.image_to_string(image, lang='neng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') 249 | org = (20,300) 250 | print("cardNumber",cardNumber) 251 | images = cv2.resize(images, (800, 600)) 252 | images = cv2.putText(images, cardNumber, org, font,fontScale, color, thickness, cv2.LINE_AA) 253 | 254 | cv2.imshow("croppedImage with cardNumber",images) 255 | cv2.waitKey(0) 256 | print("cardNumber",cardNumber) 257 | cv2.imshow("numberPartImage",image) 258 | cv2.waitKey(0) 259 | else: 260 | print("can't find the cardNumber") 261 | except cv2.error: 262 | print("can't find the position of cardNumber") 263 | except cv2.error: 264 | print("can't find the card") 265 | 266 | cv2.destroyAllWindows() 267 | -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/0.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/1.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/10.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/11.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/12.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/13.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/13.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/15.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/15.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/16.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/16.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/17.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/17.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/18.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/18.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/19.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/19.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/2.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/20.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/20.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/3.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/4.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/5.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/6.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/7.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/8.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardNumberPicture/9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardNumberPicture/9.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/0.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/1.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/10.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/12.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/13.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/13.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/14.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/14.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/15.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/15.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/16.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/16.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/17.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/17.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/18.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/18.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/2.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/3.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/4.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/5.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/6.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/7.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/8.jpg -------------------------------------------------------------------------------- /CreditCardOcrWithOpencv/modelCardPicture/9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/CreditCardOcrWithOpencv/modelCardPicture/9.jpg -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2020] [Tahoura Majlesi] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CreditCardOcr-opencv-deep-learning 2 | 3 | 4 | 5 | 6 | 7 | In this project you can get the credit card number of a credit card that is in the image. I have do this in 2 ways. The first one is with opencv and the second way is with deep learning. 8 |
9 | # 1.opencv: 10 | In this way, first this program finds the location of the card and after that it finds the card number location. By using tesseract this program can find the credit card number and then it displays it. 11 | To improve the accuracy of this, I trained the tesseract with only numbers(neng is the name of the font that i created it). 12 | you could create your own font by using jtessBox editor and Serak tesseract Trainer. 13 | This is the result: 14 |
15 |
16 | ![Rec-00430000](https://user-images.githubusercontent.com/44377951/81905129-8b8df680-95d9-11ea-9f8c-93b43bc5fd62.gif) 17 | 18 | 19 | 20 | # 2.Deep learning: 21 | loading(soon it will be added) 22 | 23 | # Prerequisites 24 |
25 | python 3+ 26 |
27 | opencv 3.4+ 28 |
29 | Numpy 30 |
31 | Tensorflow 2.0 32 |
33 | Pillow 34 |
35 | Pytesseract 5+ 36 | 37 | 38 | # Author 39 | Tahoura Majlesi 40 | 41 | 42 | # License 43 | Apache_2.0 44 | -------------------------------------------------------------------------------- /augmentingPicture.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | import keras 4 | from keras.layers.core import Dense 5 | from keras.preprocessing.image import ImageDataGenerator 6 | from PIL import Image 7 | 8 | #this code produces 50 augmented picture and then save it. 9 | def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None): 10 | if type(ims[0]) is np.ndarray: 11 | ims = np.array(ims).astype(np.uint8) 12 | if (ims.shape[-1] != 3): 13 | ims = ims.transpose((0,2,3,1)) 14 | f = plt.figure(figsize=figsize) 15 | cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows + 1 16 | for i in range(len(ims)): 17 | sp = f.add_subplot(rows, cols, i+1) 18 | sp.axis('Off') 19 | if titles is not None: 20 | sp.set_title(titles[i], fontsize=16) 21 | plt.imshow(ims[i], interpolation=None if interp else 'none') 22 | 23 | gen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1, 24 | height_shift_range=0.1, shear_range=0.15, zoom_range=0.1, 25 | channel_shift_range=10., horizontal_flip=True) 26 | image_path = "path of image which you want to make the augmented image from" 27 | image = np.expand_dims(plt.imread(image_path),0) 28 | plt.imshow(image[0]) 29 | aug_iter = gen.flow(image, seed = 0) 30 | aug_images1 = [next(aug_iter)[0].astype(np.uint8) for i in range(50)] 31 | aug_images1 = np.array(aug_images1) 32 | 33 | i=0 34 | for im in (aug_images1): 35 | im = Image.fromarray(im) 36 | im.save("path to save the augmented image"+str(i)+".jpg") 37 | i+=1 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /demo/demo.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/demo/demo.mp4 -------------------------------------------------------------------------------- /neng.traineddata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahoora78/CreditCardOcr-opencv-deep-learning/ed4482b4760759f26bd7ea6ece6e2274668059ae/neng.traineddata -------------------------------------------------------------------------------- /opencv-featureDetection: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import pytesseract 4 | import tempfile 5 | from PIL import Image 6 | 7 | 8 | def convertingPintToTheFourDimensionalArray(pts): 9 | rect = [[0, 0], [0, 0], [0, 0], [0, 0]] 10 | rect[0][0] = (pts[0][0][0]) 11 | rect[0][1] = (pts[0][0][1]) 12 | 13 | rect[1][0] = (pts[1][0][0]) 14 | rect[1][1] = (pts[1][0][1]) 15 | 16 | rect[2][0] = (pts[2][0][0]) 17 | rect[2][1] = (pts[2][0][1]) 18 | 19 | rect[3][0] = (pts[3][0][0]) 20 | rect[3][1] = (pts[3][0][1]) 21 | return rect 22 | 23 | 24 | def order_points(pts): 25 | pts = convertingPintToTheFourDimensionalArray(pts) 26 | rect = np.zeros((4, 2), dtype="float32") 27 | for j in range(4): 28 | for i in range(4): 29 | if pts[i][0] >= pts[j][0]: 30 | pts[i], pts[j] = pts[j], pts[i] 31 | if pts[1][1] <= pts[0][1]: 32 | rect[0] = pts[1] 33 | rect[3] = pts[0] 34 | else: 35 | rect[0] = pts[0] 36 | rect[3] = pts[1] 37 | pts = np.delete(pts, 0, 0) 38 | pts = np.delete(pts, 0, 0) 39 | if pts[1][1] <= pts[0][1]: 40 | rect[1] = pts[1] 41 | rect[2] = pts[0] 42 | else: 43 | rect[1] = pts[0] 44 | rect[2] = pts[1] 45 | return rect 46 | 47 | def four_point_transform(image, pts): 48 | rect = order_points(pts) 49 | (tl, tr, br, bl) = rect 50 | widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) 51 | widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) 52 | maxWidth = max(int(widthA), int(widthB)) 53 | heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) 54 | heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) 55 | maxHeight = max(int(heightA), int(heightB)) 56 | dst = np.array([ 57 | [0, 0], 58 | [maxWidth - 1, 0], 59 | [maxWidth - 1, maxHeight - 1], 60 | [0, maxHeight - 1]], dtype = "float32") 61 | M = cv2.getPerspectiveTransform(rect, dst) 62 | warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight)) 63 | return warped 64 | 65 | def findingTotalCard(testingPath,modelPath): 66 | numberOfModelCard = 19 67 | testImage = cv2.imread(testingPath) 68 | testImage = cv2.resize(testImage,(800,600)) 69 | cv2.imshow("original image", testImage) 70 | cv2.waitKey(0) 71 | testingImage = cv2.imread(testingPath) 72 | for i in range(numberOfModelCard): 73 | x , image = findingCardPosition(testingPath,modelPath+str(i)+".jpg") 74 | if x==1: 75 | cardImage = image 76 | return cardImage 77 | 78 | def findingTotalCardNumber(testingImage,modelPath): 79 | find =0 80 | cardImage = testingImage 81 | numberOfCardNumberPicture=21 82 | imager=cv2.imread(modelPath+str(0)+".jpg") 83 | for i in range(numberOfCardNumberPicture): 84 | x,image = findingCardNumbersPosition(testingImage,modelPath+str(i)+".jpg") 85 | if x == 1: 86 | find=1 87 | cardImage = image 88 | break 89 | return cardImage,find 90 | def findingCardPosition(testingPath,modelPath): 91 | testingImage = cv2.imread(testingPath) 92 | img = cv2.imread(modelPath, cv2.IMREAD_GRAYSCALE) # queryiamge 93 | sift = cv2.xfeatures2d.SIFT_create() 94 | kp_image, desc_image = sift.detectAndCompute(img, None) 95 | 96 | index_params = dict(algorithm=0, trees=5) 97 | search_params = dict() 98 | flann = cv2.FlannBasedMatcher(index_params, search_params) 99 | frame = testingImage 100 | 101 | grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # trainimage 102 | kp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) 103 | matches = flann.knnMatch(desc_image, desc_grayframe, k=2) 104 | good_points = [] 105 | for m, n in matches: 106 | if m.distance < 0.5 * n.distance: 107 | good_points.append(m) 108 | 109 | # Homography 110 | if len(good_points) > 12: 111 | query_pts = np.float32([kp_image[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2) 112 | train_pts = np.float32([kp_grayframe[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2) 113 | matrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) 114 | matches_mask = mask.ravel().tolist() 115 | h, w = img.shape 116 | pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2) 117 | dst = cv2.perspectiveTransform(pts, matrix) 118 | homography = cv2.polylines(frame, [np.int32(dst)], True, (0, 0, 255), 1) 119 | croped_image = four_point_transform(frame,np.int32(dst)) 120 | cv2.destroyAllWindows() 121 | return 1,croped_image 122 | else: 123 | print("can't find card position") 124 | return 2,frame 125 | cv2.destroyAllWindows() 126 | def findingCardNumbersPosition(testingImage,modelPath): 127 | img = cv2.imread(modelPath, cv2.IMREAD_GRAYSCALE) # queryiamge 128 | # Features 129 | sift = cv2.xfeatures2d.SIFT_create() 130 | kp_image, desc_image = sift.detectAndCompute(img, None) 131 | # Feature matching 132 | index_params = dict(algorithm=0, trees=5) 133 | search_params = dict() 134 | flann = cv2.FlannBasedMatcher(index_params, search_params) 135 | frame = testingImage 136 | grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # trainimage 137 | kp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None) 138 | matches = flann.knnMatch(desc_image, desc_grayframe, k=2) 139 | good_points = [] 140 | for m, n in matches: 141 | if m.distance < 0.5 * n.distance: 142 | good_points.append(m) 143 | 144 | if len(good_points) > 10: 145 | query_pts = np.float32([kp_image[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2) 146 | train_pts = np.float32([kp_grayframe[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2) 147 | matrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0) 148 | matches_mask = mask.ravel().tolist() 149 | 150 | h, w = img.shape 151 | pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2) 152 | dst = cv2.perspectiveTransform(pts, matrix) 153 | hq, wq, e = frame.shape 154 | croped_image = four_point_transform(frame,np.int32(dst)) 155 | cv2.destroyAllWindows() 156 | return 1, croped_image 157 | else: 158 | print("can't find card number position") 159 | return 2, frame 160 | cv2.destroyAllWindows() 161 | 162 | def process_image_for_ocr(file_path): 163 | # TODO : Implement using opencv 164 | temp_filename = set_image_dpi(file_path) 165 | im_new = remove_noise_and_smooth(temp_filename) 166 | im_new = clearNoise(im_new) 167 | return im_new 168 | 169 | def set_image_dpi(file_path): 170 | IMAGE_SIZE = 1800 171 | BINARY_THREHOLD = 180 172 | im = Image.open(file_path) 173 | length_x, width_y = im.size 174 | factor = max(1, int(IMAGE_SIZE / length_x)) 175 | size = factor * length_x, factor * width_y 176 | im_resized = im.resize(size, Image.ANTIALIAS) 177 | temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') 178 | temp_filename = temp_file.name 179 | im_resized.save(temp_filename, dpi=(300, 300)) 180 | return temp_filename 181 | 182 | def image_smoothening(img): 183 | BINARY_THREHOLD = 180 184 | ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) 185 | ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 186 | blur = cv2.GaussianBlur(th2, (1, 1), 0) 187 | ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 188 | return th3 189 | 190 | def remove_noise_and_smooth(file_name): 191 | img = cv2.imread(file_name, 0) 192 | filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 193 | 3) 194 | kernel = np.ones((1, 1), np.uint8) 195 | opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel) 196 | closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) 197 | img = image_smoothening(img) 198 | or_image = cv2.bitwise_or(img, closing) 199 | return or_image 200 | def clearNoise(image): 201 | kernel = np.ones((5,5),np.uint8) 202 | image = cv2.dilate(image,kernel,iterations = 1) 203 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 204 | for i in range(30): 205 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 206 | image = cv2.erode(image,kernel,iterations = 1) 207 | image = cv2.dilate(image,kernel,iterations = 1) 208 | image = cv2.dilate(image,kernel,iterations = 1) 209 | for i in range(100): 210 | image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) 211 | image = cv2.erode(image,kernel,iterations = 1) 212 | image = cv2.erode(image,kernel,iterations = 1) 213 | return image 214 | 215 | def ocr(image): 216 | image = image 217 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 218 | cv2.imshow("Image", gray) 219 | 220 | gray = cv2.medianBlur(gray, 3) 221 | 222 | filename = "newImage.jpg" 223 | cv2.imwrite(filename, gray) 224 | 225 | text = pytesseract.image_to_string(Image.open(filename), lang='neng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') 226 | print(text) 227 | cv2.imshow("Output", gray) 228 | cv2.waitKey(0) 229 | return text 230 | 231 | def findTheCardNumber(pathOfImage): 232 | font = cv2.FONT_HERSHEY_SIMPLEX 233 | org = (50, 50) 234 | fontScale = 2 235 | color = (0, 50, 255) 236 | thickness = 5 237 | modelCardPicturesFolderPath = "CreditCardOcrWithOpencv\\modelCardPicture\\" 238 | modelCardNumberPicturesFolderPath = "CreditCardOcrWithOpencv\\modelCardNumberPicture\\" 239 | testingImagePath = pathOfImage 240 | try: 241 | images = findingTotalCard(testingImagePath,modelCardPicturesFolderPath) 242 | try: 243 | image,find = findingTotalCardNumber(images,modelCardNumberPicturesFolderPath) 244 | if find==1: 245 | w,h,c = image.shape 246 | image = cv2.resize(image, (int(h/2), int(w/2))) 247 | path = "testing picture\\newImage.jpg" 248 | cardNumber = pytesseract.image_to_string(image, lang='neng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') 249 | org = (20,300) 250 | print("cardNumber",cardNumber) 251 | images = cv2.resize(images, (800, 600)) 252 | images = cv2.putText(images, cardNumber, org, font,fontScale, color, thickness, cv2.LINE_AA) 253 | 254 | cv2.imshow("croppedImage with cardNumber",images) 255 | cv2.waitKey(0) 256 | print("cardNumber",cardNumber) 257 | cv2.imshow("numberPartImage",image) 258 | cv2.waitKey(0) 259 | else: 260 | print("can't find the cardNumber") 261 | except cv2.error: 262 | print("can't find the position of cardNumber") 263 | except cv2.error: 264 | print("can't find the card") 265 | 266 | cv2.destroyAllWindows() 267 | 268 | #how to run it:)) 269 | findTheCardNumber("enter your path of image") 270 | --------------------------------------------------------------------------------