Package: document-scanner-sdk
Python Document Scanner SDKThe project is a Python binding toDynamsoft C/C++ Document Scanner SDK. It aims to help developers quickly build desktop document scanner applications in Python on Windows and Linux.About Dynamsoft Document ScannerGet a30-day FREE trial licenseto activate the SDK.Supported Python EditionPython 3.xDependenciespipinstallopencv-pythonCommand-line Usage# Scan documents from images$scandocument-f<file-name>-l<license-key># Scan documents from camera video stream$scandocument-c1-l<license-key>Quick StartScan documents from an image file:importargparseimportdocscannerimportsysimportnumpyasnpimportcv2importtimedefshowNormalizedImage(name,normalized_image):mat=docscanner.convertNormalizedImage2Mat(normalized_image)cv2.imshow(name,mat)returnmatdefprocess_file(filename,scanner):image=cv2.imread(filename)results=scanner.detectMat(image)forresultinresults:x1=result.x1y1=result.y1x2=result.x2y2=result.y2x3=result.x3y3=result.y3x4=result.x4y4=result.y4normalized_image=scanner.normalizeBuffer(image,x1,y1,x2,y2,x3,y3,x4,y4)showNormalizedImage("Normalized Image",normalized_image)cv2.drawContours(image,[np.int0([(x1,y1),(x2,y2),(x3,y3),(x4,y4)])],0,(0,255,0),2)cv2.imshow('Document Image',image)cv2.waitKey(0)normalized_image.save(str(time.time())+'.png')print('Image saved')defscandocument():"""Command-line script for scanning documents from a given image"""parser=argparse.ArgumentParser(description='Scan documents from an image file')parser.add_argument('-f','--file',help='Path to the image file')parser.add_argument('-l','--license',default='',type=str,help='Set a valid license key')args=parser.parse_args()# print(args)try:filename=args.filelicense=args.licenseiffilenameisNone:parser.print_help()return# set licenseiflicense=='':docscanner.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")else:docscanner.initLicense(license)# initialize mrz scannerscanner=docscanner.createInstance()ret=scanner.setParameters(docscanner.Templates.color)iffilenameisnotNone:process_file(filename,scanner)exceptExceptionaserr:print(err)sys.exit(1)scandocument()Scan documents from camera video stream:importargparseimportdocscannerimportsysimportnumpyasnpimportcv2importtimeg_results=Noneg_normalized_images=[]defcallback(results):globalg_resultsg_results=resultsdefshowNormalizedImage(name,normalized_image):mat=docscanner.convertNormalizedImage2Mat(normalized_image)cv2.imshow(name,mat)returnmatdefprocess_video(scanner):scanner.addAsyncListener(callback)cap=cv2.VideoCapture(0)whileTrue:ret,image=cap.read()ch=cv2.waitKey(1)ifch==27:breakelifch==ord('n'):# normalize imageifg_results!=None:g_normalized_images=[]index=0forresulting_results:x1=result.x1y1=result.y1x2=result.x2y2=result.y2x3=result.x3y3=result.y3x4=result.x4y4=result.y4normalized_image=scanner.normalizeBuffer(image,x1,y1,x2,y2,x3,y3,x4,y4)g_normalized_images.append((str(index),normalized_image))mat=showNormalizedImage(str(index),normalized_image)index+=1elifch==ord('s'):# save imagefordataing_normalized_images:# cv2.imwrite('images/' + str(time.time()) + '.png', image)cv2.destroyWindow(data[0])data[1].save(str(time.time())+'.png')print('Image saved')g_normalized_images=[]ifimageisnotNone:scanner.detectMatAsync(image)ifg_results!=None:forresulting_results:x1=result.x1y1=result.y1x2=result.x2y2=result.y2x3=result.x3y3=result.y3x4=result.x4y4=result.y4cv2.drawContours(image,[np.int0([(x1,y1),(x2,y2),(x3,y3),(x4,y4)])],0,(0,255,0),2)cv2.putText(image,'Press "n" to normalize image',(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,255),2)cv2.putText(image,'Press "s" to save image',(10,60),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,255),2)cv2.putText(image,'Press "ESC" to exit',(10,90),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,255),2)cv2.imshow('Document Scanner',image)defscandocument():"""Command-line script for scanning documents from camera video stream."""parser=argparse.ArgumentParser(description='Scan documents from camera')parser.add_argument('-c','--camera',default=False,type=bool,help='Whether to show the image')parser.add_argument('-l','--license',default='',type=str,help='Set a valid license key')args=parser.parse_args()# print(args)try:license=args.licensecamera=args.cameraifcameraisFalse:parser.print_help()return# set licenseiflicense=='':docscanner.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")else:docscanner.initLicense(license)# initialize mrz scannerscanner=docscanner.createInstance()ret=scanner.setParameters(docscanner.Templates.color)ifcameraisTrue:process_video(scanner)exceptExceptionaserr:print(err)sys.exit(1)scandocument()Methodsdocscanner.initLicense('YOUR-LICENSE-KEY')# set the license keydocscanner.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")docscanner.createInstance()# create a Document Scanner instancescanner=docscanner.createInstance()detectFile(filename)# do edge detection from an image fileresults=scanner.detectFile(<filename>)detectMat(Mat image)# do edge detection from Matimage=cv2.imread(<filename>)results=scanner.detectMat(image)forresultinresults:x1=result.x1y1=result.y1x2=result.x2y2=result.y2x3=result.x3y3=result.y3x4=result.x4y4=result.y4setParameters(Template)# Select color, binary or grayscale templatescanner.setParameters(docscanner.Templates.color)addAsyncListener(callback function)# start a native thread to run document scanning tasksdetectMatAsync(<opencv mat data>)# put a document scanning task into the native queuedefcallback(results):forresultinresults:print(result.x1)print(result.y1)print(result.x2)print(result.y2)print(result.x3)print(result.y3)print(result.x4)print(result.y4)importcv2image=cv2.imread(<filename>)scanner.addAsyncListener(callback)scanner.detectMatAsync(image)sleep(5)normalizeBuffer(mat, x1, y1, x2, y2, x3, y3, x4, y4)# do perspective correction from Matnormalized_image=scanner.normalizeBuffer(image,x1,y1,x2,y2,x3,y3,x4,y4)normalizeFile(filename, x1, y1, x2, y2, x3, y3, x4, y4)# do perspective correction from a filenormalized_image=scanner.normalizeFile(<filename>,x1,y1,x2,y2,x3,y3,x4,y4)normalized_image.save(filename)# save the normalized image to a filenormalized_image.save(<filename>)normalized_image.recycle()# release the memory of the normalized imageclearAsyncListener()# stop the native thread and clear the registered Python functionC/C++ APITo customize Python API based on C/C++, please refer to theonline documentation.How to Build the Python Document Scanner ExtensionCreate a source distribution:pythonsetup.pysdistsetuptools:pythonsetup_setuptools.pybuild
pythonsetup_setuptools.pydevelopBuild wheel:pipwheel.--verbose# Orpythonsetup.pybdist_wheel