当前位置:网站首页>Project practice: parameters of pycharm configuration for credit card digital recognition and how to use opencv in Anaconda
Project practice: parameters of pycharm configuration for credit card digital recognition and how to use opencv in Anaconda
2022-06-26 08:07:00 【Dotian convenience store】
@TOC
Preface
I'm in the front anaconda Installed in opencv,(anaconda3-5.2.0+python3.6 install opencv-python3.4.1.15 Steps and processes ), Now want to be in pycharm It is used in opencv, I don't want to install it again , Want to use anaconda Medium , besides ,anaconda There are many other things that have been configured in the .
One 、 New projects
Click on the taskbar file->new project, stay Location Select the folder for the new project ( Create an empty folder in advance ).
Then it should be the first button by default , Do you want us to use anaconda Things in , So you have to choose anaconda Interpreter .
And then in Interpreter look for anaconda Medium python.exe

One way is , After the project is built as usual , Go again file->setting Choose from anaconda Medium python.exe, I tried , This can only be done with anaconda Medium python, But the bag inside can't be used ,opencv Can not use . Only in pycharm Reload in , Or use pip loading .
Choose when you are building a project anaconda Interpreter , Then I'll go to file->setting see , You will see that it has been selected , And there's a lot of anaconda Your bag can be used .
Reference article : Want to be in pycharm Use in anaconda Installed opencv package
Two 、 Configuration parameters

I can't find the file name by right clicking here Edit project, So look for the buttons in the picture , Run the file and you will have the information of the page .
Enter the parameters in the red box .
--image The path name where you store your pictures \ Specific picture name --template The path name where you store your pictures \ Specific picture name
Here's the thing to note , The path for storing pictures should not appear in Chinese , Use... In the back cv2.imread Function time , An error will be reported when the program is running .( Specific reference article : Path error reporting )
Reference article :pychram How to configure corresponding parameters Step two of
3、 ... and 、 Points to note for successful operation
1、 No, imutils package , It needs to be installed :pip install imutils
2、cv2.findContours This function , In the new opencv And old opencv It's different . The new version does not have the first parameter , I use the old version .( Refer to the article here :python call cv2.findContours Times wrong )ref_, refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
Four 、 The overall code
# Import toolkit
from imutils import contours
import numpy as np
import argparse
import cv2
#import myutils
# Set parameters
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to input image")
ap.add_argument("-t", "--template", required=True,
help="path to template OCR-A image")
args = vars(ap.parse_args())
# Specify the type of credit card
FIRST_NUMBER = {
"3": "American Express",
"4": "Visa",
"5": "MasterCard",
"6": "Discover Card"
}
def sort_contours(cnts, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in cnts] # Use the smallest rectangle , Wrap the shapes you find x,y,h,w
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b: b[1][i], reverse=reverse))
return cnts, boundingBoxes
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if width is None:
r = height / float(h)
dim = (int(w * r), height)
else:
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized
# Graphic display
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Read a template image
img = cv2.imread(args["template"])
cv_show('img', img)
# grayscale
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv_show('ref', ref)
# Binary image
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv_show('ref', ref)
# Calculate the contour
# cv2.findContours() The parameters accepted by the function are binary graphs , Black and white ( It's not grayscale ),cv2.RETR_EXTERNAL Only the outer contour is detected ,cv2.CHAIN_APPROX_SIMPLE Keep only the end coordinates
# Back to list Each element in is an outline in the image
ref_, refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, refCnts, -1, (0, 0, 255), 3)
cv_show('img', img)
print(np.array(refCnts).shape)
#refCnts = myutils.sort_contours(refCnts, method="left-to-right")[0] # Sort , From left to right , From top to bottom
refCnts = sort_contours(refCnts, method="left-to-right")[0] # Sort , From left to right , From top to bottom
digits = {}
# Traverse every contour
for (i, c) in enumerate(refCnts):
# Calculate the circumscribed rectangle and resize To the right size
(x, y, w, h) = cv2.boundingRect(c)
roi = ref[y:y + h, x:x + w]
roi = cv2.resize(roi, (57, 88))
# Each number corresponds to each template
digits[i] = roi
# Initialize convolution kernel
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
# Read input image , Preprocessing
image = cv2.imread(args["image"])
cv_show('image', image)
image = resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv_show('gray', gray)
# Hat operation , Highlight brighter areas
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)
cv_show('tophat', tophat)
#
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, # ksize=-1 Equivalent to using 3*3 Of
ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")
print(np.array(gradX).shape)
cv_show('gradX', gradX)
# By closing ( Inflate first , Corrode again ) Put the numbers together
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
cv_show('gradX', gradX)
# THRESH_OTSU Will automatically find the right threshold , Suitable for bimodal , The threshold parameter needs to be set to 0
thresh = cv2.threshold(gradX, 0, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv_show('thresh', thresh)
# Another close operation
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) # Another close operation
cv_show('thresh', thresh)
# Calculate the contour
thresh_,threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img, cnts, -1, (0, 0, 255), 3)
cv_show('img', cur_img)
locs = []
# Traverse the outline
for (i, c) in enumerate(cnts):
# Calculate rectangle
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
# Choose the right area , According to the actual task , It's basically a set of four numbers
if ar > 2.5 and ar < 4.0:
if (w > 40 and w < 55) and (h > 10 and h < 20):
# The right ones stay
locs.append((x, y, w, h))
# Sort the matching contours from left to right
locs = sorted(locs, key=lambda x: x[0])
output = []
# Go through the numbers in each profile
for (i, (gX, gY, gW, gH)) in enumerate(locs):
# initialize the list of group digits
groupOutput = []
# Extract each group from the coordinates
group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
cv_show('group', group)
# Preprocessing
group = cv2.threshold(group, 0, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv_show('group', group)
# Calculate the outline of each group
group_,digitCnts, hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
digitCnts = contours.sort_contours(digitCnts,
method="left-to-right")[0]
# Calculate each value in each group
for c in digitCnts:
# Find the outline of the current value ,resize To the right size
(x, y, w, h) = cv2.boundingRect(c)
roi = group[y:y + h, x:x + w]
roi = cv2.resize(roi, (57, 88))
cv_show('roi', roi)
# Calculate the match score
scores = []
# Calculate each score in the template
for (digit, digitROI) in digits.items():
# Template matching
result = cv2.matchTemplate(roi, digitROI,
cv2.TM_CCOEFF)
(_, score, _, _) = cv2.minMaxLoc(result)
scores.append(score)
# Get the most appropriate number
groupOutput.append(str(np.argmax(scores)))
# Draw out
cv2.rectangle(image, (gX - 5, gY - 5),
(gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)
# Get the results
output.extend(groupOutput)
# Print the results
print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image)
cv2.waitKey(0)
边栏推荐
- What if the service in Nacos cannot be deleted?
- Automatic backup of MySQL database in the early morning with Linux
- Household enterprises use WMS warehouse management system. What are the changes
- Esp32-c3 introductory tutorial WiFi part ⑥ - WIFI intelligent distribution network based on serial port
- Can the warehouse management system help enterprises reduce storage costs
- Yyds dry inventory Druid connection pool usage
- I want to open a stock account at a discount. How do I do it? Is it safe to open a mobile account?
- MySQL practice: 1 Common database commands
- Data governance: from top project to data culture!
- MySQL practice: 2 Table definition and SQL classification
猜你喜欢

Wifi-802.11 2.4G band 5g band channel frequency allocation table

The difference between setstoragesync and setstorage

Can the warehouse management system help enterprises reduce storage costs

Seven important reasons for responsive Web Design

Oracle database self study notes

Tsinghua Yaoban chendanqi won Sloan award! He is a classmate with last year's winner Ma Tengyu. His doctoral thesis is one of the hottest in the past decade

Database learning notes I

Real machine debugging of uniapp custom base
![[NLP] vector retrieval model landing: Bottleneck and solution!](/img/c4/784534e5504dfee1c989d19255c31b.jpg)
[NLP] vector retrieval model landing: Bottleneck and solution!

Chapter 5 (array)
随机推荐
Oracle database self study notes
Uni app is similar to Taobao in selecting multiple specifications of commodities (inventory judgment)
buuresevewp
Esp32-c3 introductory tutorial WiFi part ⑥ - WIFI intelligent distribution network based on serial port
Late 2021 plan
Uni app installation and project directory (hbuilder configuration)
Project management learning
Win11 open folder Caton solution summary
How to debug plug-ins using vs Code
This article will take you to learn in detail what is FTTH
MySQL practice: 2 Table definition and SQL classification
Web technology sharing | webrtc recording video stream
Open a file at line with'filename:line'syntax - open a file at line with'filename:line' syntax
I want to open a stock account at a discount. How do I do it? Is it safe to open a mobile account?
ReW_ p
Wechat applet beginner level chapter
What is Wi Fi 6 (802.11ax)? Why is Wi Fi 6 important?
Yyds dry inventory kubernetes easy service discovery and load balancing (11)
What are the key points of turnover box management in warehouse management
Area of Blue Bridge Cup 2 circle