Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
Last Updated :
23 May, 2024
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build an automatic document scanner using OpenCV.
Automatic Document Scanner using OpenCV
An automatic document scanner using OpenCV involves several steps to detect, crop, and enhance the document in an image. Typically, the process involves the following steps:
In this tutorial, we will be using a test image on which we will implement the Automatic Document Scanner. We will be executing every step mentioned above.
Image used for Demonstration in this article:

Demo image
Steps to Implement Automatic Document Scanner Using OpenCV
Step 1: Installing OpenCV
We are using openCV which is an open-source computer vision and machine learning library designed to facilitate various computer vision applications, and we install it via:
pip install opencv-python
Step 2: Creating project folder
We will need to create a project folder in our system for us to store digital documents.
- Create another directory named ‘Scanned’ to store digital documents.
- Create 2 python files named ‘Doc_Scanner.py’ and ‘utlis.py’.
The File Structure will be:

File Structure
Step 3 : Importing necessary libraries
We at first import necessary libraries in the Doc_Scanner.py file.
Python
import cv2
import numpy as np
import utlis # Importing module named utlis
Step 4: Setting Up the Video Camera
The code sets up a video capture object to access a webcam feed from the specified URL. It adjusts the camera properties for resolution and brightness.
Python
webCamFeed = False
url = 'http://192.168.1.6:8080/video'
cap = cv2.VideoCapture(url)
cap.set(10, 160)
heightImg = 640
widthImg = 480
Step 5 : Checking whether frame is being loaded
The code segment initializes trackbars for parameter tuning, then enters a loop to continuously read frames from the video capture object. It checks if the frame is successfully read and if it’s not empty, continuing the loop accordingly.
Python
utlis.initializeTrackbars()
count = 0
while True:
success, img = cap.read()
if success:
print("Frame read successfully")
else:
print("Failed to read frame")
break
if not img.size: # Check if the frame is empty
print("Empty frame")
continue
Step 6: Image Preprocessing
The code resizes the captured frame to the specified width and height, creates a blank image for debugging purposes, converts the resized frame to grayscale, and applies Gaussian blur to reduce noise in the image.
Python
img = cv2.resize(img, (widthImg, heightImg)) # RESIZE FRAME
imgBlank = np.zeros((heightImg, widthImg, 3), np.uint8) # CREATE A BLANK IMAGE FOR TESTING DEBUGGING IF REQUIRED
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # CONVERT IMAGE TO GRAY SCALE
imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1) # ADD GAUSSIAN BLUR
Step 7: Edge Detection
The code segment retrieves the threshold values from trackbars, then applies Canny edge detection to the blurred grayscale image using these threshold values.
Python
thres = utlis.valTrackbars() # GET TRACK BAR VALUES FOR THRESHOLDS
imgThreshold = cv2.Canny(imgBlur, thres[0], thres[1]) # APPLY CANNY BLUR
Output:

Step 8: Finding biggest contour
The block performs morphological operations like dilation and erosion on the thresholded image, finds contours in the processed image, draws these contours on a copy of the original image for display purposes, identifies the biggest contour, reorders its points, and draws a rectangle around it. Then, it prepares points for perspective transformation and warps the original image to a bird’s-eye view based on the identified contour.
Python
kernel = np.ones((5, 5))
imgDial = cv2.dilate(imgThreshold, kernel, iterations=2) # APPLY DILATION
imgThreshold = cv2.erode(imgDial, kernel, iterations=1) # APPLY EROSION
## FIND ALL CONTOURS
imgContours = img.copy() # COPY IMAGE FOR DISPLAY PURPOSES
imgBigContour = img.copy() # COPY IMAGE FOR DISPLAY PURPOSES
contours, hierarchy = cv2.findContours(imgThreshold, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE) # FIND ALL CONTOURS
cv2.drawContours(imgContours, contours, -1, (0, 255, 0), 10) # DRAW ALL DETECTED CONTOURS
# FIND THE BIGGEST CONTOUR
biggest, maxArea = utlis.biggestContour(contours) # FIND THE BIGGEST CONTOUR
if biggest.size != 0:
biggest = utlis.reorder(biggest)
cv2.drawContours(imgBigContour, biggest, -1, (0, 255, 0), 20) # DRAW THE BIGGEST CONTOUR
imgBigContour = utlis.drawRectangle(imgBigContour, biggest, 2)
pts1 = np.float32(biggest) # PREPARE POINTS FOR WARP
pts2 = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]]) # PREPARE POINTS FOR WARP
matrix = cv2.getPerspectiveTransform(pts1, pts2)
imgWarpColored = cv2.warpPerspective(img, matrix, (widthImg, heightImg))
Output:
-300.png)
Step 9: Configuring The Image
Thie code snippet processes the warped colored image by cropping 20 pixels from each side, then resizing it to the original dimensions. It applies adaptive thresholding, bitwise NOT operation, and median blur to enhance the quality of the image for further processing.
Python
# REMOVE 20 PIXELS FROM EACH SIDE
imgWarpColored = imgWarpColored[20:imgWarpColored.shape[0] - 20, 20:imgWarpColored.shape[1] - 20]
imgWarpColored = cv2.resize(imgWarpColored, (widthImg, heightImg))
# APPLY ADAPTIVE THRESHOLD
imgWarpGray = cv2.cvtColor(imgWarpColored, cv2.COLOR_BGR2GRAY)
imgAdaptiveThre = cv2.adaptiveThreshold(imgWarpGray, 255, 1, 1, 7, 2)
imgAdaptiveThre = cv2.bitwise_not(imgAdaptiveThre)
imgAdaptiveThre = cv2.medianBlur(imgAdaptiveThre, 3)
# Image Array for Display
imageArray = ([img, imgGray, imgThreshold, imgContours],
[imgBigContour, imgWarpColored, imgWarpGray, imgAdaptiveThre])
# WRITE IMAGE
cv2.imwrite("Scanned/myImage" + str(count) + ".jpg", imgWarpColored)
count += 1
else:
imageArray = ([img, imgGray, imgThreshold, imgContours],
[imgBlank, imgBlank, imgBlank, imgBlank])
# LABELS FOR DISPLAY
labels = [["Original", "Gray", "Threshold", "Contours"],
["Biggest Contour", "Warp Perspective", "Warp Gray", "Adaptive Threshold"]]
stackedImage = utlis.stackImages(imageArray, 0.75, labels)
cv2.imshow("Result", stackedImage)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Step 10 : Saving the Image
This part of the code listens for the ‘s’ key press event. When the ‘s’ key is pressed, it saves the current warped colored image to a file, overlays a green rectangle with the text “Scan Saved” onto the displayed image, and then updates the display for 300 milliseconds before resuming. Additionally, it increments the count for saving subsequent images with unique names.
Python
# SAVE IMAGE WHEN 's' key is pressed
if cv2.waitKey(1) & 0xFF == ord('s'):
cv2.imwrite("Scanned/myImage" + str(count) + ".jpg", imgWarpColored)
cv2.rectangle(stackedImage, ((int(stackedImage.shape[1] / 2) - 230), int(stackedImage.shape[0] / 2) + 50),
(1100, 350), (0, 255, 0), cv2.FILLED)
cv2.putText(stackedImage, "Scan Saved", (int(stackedImage.shape[1] / 2) - 200, int(stackedImage.shape[0] / 2)),
cv2.FONT_HERSHEY_DUPLEX, 3, (0, 0, 255), 5, cv2.LINE_AA)
cv2.imshow('Result', stackedImage)
cv2.waitKey(300)
count += 1
Step 11: Closing the window
This part of the code releases the video capture object and closes all OpenCV windows to release system resources and terminate the program cleanly.
Python
cap.release()
cv2.destroyAllWindows()
Output:

Scanned Document
In this article, we’ve walked through the process of building an automatic document scanner using OpenCV. By following the outlined steps, we were able to implement each stage of the document scanning process, from preprocessing the image to detecting edges, finding contours, and finally saving the scanned document.
Please Login to comment...