The Wayback Machine - https://web.archive.org/web/20240708193411/https://www.geeksforgeeks.org/automatic-document-scanner-using-opencv-opencv-document-scanner/
Open In App

Automatic Document Scanner using OpenCV (OpenCV Document Scanner)

Last Updated : 23 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

myImage358

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

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:

gfggggg

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:

GFFGFGFGF-min-(1)

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:

gfg

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.



Similar Reads

Automatic color correction with OpenCV and Python
Colour correction is an important aspect of image processing and is used to correct any colour imbalances in an image. OpenCV is an open-source library for computer vision and image processing tasks that provides several functions and tools to analyze and manipulate images. In this tutorial, we will explore how to perform automatic colour correctio
3 min read
Webcam QR code scanner using OpenCV
In this article, we're going to see how to perform QR code scanning using a webcam. Before starting, You need to know how this process is going to work. Firstly you need to open your webcam, and you've to run your python program to make it ready to scan the QR code. You can take the Qr code picture on your mobile and show the picture in front of yo
3 min read
Automatic Speech Recognition using CTC
We use speeches to express ourselves. But sometimes it is crucial to store our speech in text format. One such technology is Automatic Speech Recognition which converts spoken language into written text. In this article, we will implement Automatic Speech Recognition using Connectionist Temporal Classification (CTC). In various real-time applicatio
8 min read
Automatic Speech Recognition using Whisper
Automatic Speech Recognition (ASR) can be simplified as artificial intelligence transforming spoken language into text. Its historical journey dates back to a time when developing ASR posed significant challenges. Addressing diverse factors such as variations in voices, accents, background noise, and speech patterns proved to be formidable obstacle
10 min read
Automatic Number Plate Recognition System using EasyOCR
Automatic License/Number Plate Recognition (ANPR) is an image processing technique used to identify a car based on its number plate. In this article, we'll walk through the steps to implement ANPR using Python. Techniques for ANPR are: License Plate Recognition with OpenCV and Tesseract OCRAutomatic License/Number Plate Recognition System with Easy
7 min read
Graphs, Automatic Differentiation and Autograd in PyTorch
Graphs, Automatic Differentiation and Autograd are powerful tools in PyTorch that can be used to train deep learning models. Graphs are used to represent the computation of a model, while Automatic Differentiation and Autograd allow the model to learn by updating its parameters during training. In this article, we will explore the concepts behind t
7 min read
Automatic differentiation in TensorFlow
In this post, we'll go over the concepts underlying TensorFlow's automated differentiation and provide helpful, step-by-step instructions and screenshots to demonstrate how to utilize it. Automatic differentiation (AD) is a fundamental technique in machine learning, particularly in frameworks like TensorFlow. It is crucial for model optimization te
5 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
What happens when Block Scanner Detects a Corrupted Data Block?
Data integrity is a critical aspect of computer systems, ensuring that information remains accurate, steady, and reliable during its lifecycle. One of the critical components in maintaining this integrity is the block scanner. When a block scanner detects a corrupted data block, several processes and mechanisms come into play to handle the situatio
9 min read