使用python和opencv去除试卷痕迹

小朋友做试卷,有时需要重新做一遍。才2年级,使用的是铅笔,批改用的是红笔,就想着自己使用opencv处理下,直接恢复到初始的空白试卷。

想法比较简单,通过灰度图和阀值,过滤掉铅笔的痕迹。使用提取红色通道及阀值,过滤掉红色的批改痕迹。再将两个图做一次“或”,就可以得到需要的空白试卷了。

关于红色的过滤参考了:https://blog.csdn.net/wl_Honest/article/details/107569135?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161872855116780264052508%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=161872855116780264052508&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-8-107569135.pc_search_result_hbase_insert&utm_term=opencv+%E5%8E%BB%E9%99%A4%E7%BA%A2%E8%89%B2

 

# -*- encoding: utf-8 -*-
import cv2
import numpy as np
 
 
class SealRemove(object):

    def remove_red_seal(self, image):
        # 获得红色通道
        blue_c, green_c, red_c = cv2.split(image)
        # 多传入一个参数cv2.THRESH_OTSU,并且把阈值thresh设为0,算法会找到最优阈值
        thresh, ret = cv2.threshold(red_c, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        # 实测调整为95%效果好一些
        filter_condition = int(thresh * 0.95)
 
        nominator_thresh, red_thresh = cv2.threshold(red_c, filter_condition, 255, cv2.THRESH_BINARY)
        return red_thresh

 
    def shijuanqingli(self, image):
        # img = cv2.imread(image, 0)
        thresh, dst1 = cv2.threshold(image, 50, 255, cv2.THRESH_BINARY)
        dst1_without_pen = dst1
        return dst1_without_pen

    def join_image(self, img_without_red, dst1_without_pen):
        ret = cv2.bitwise_or(img_without_red, dst1_without_pen)
        return ret

if __name__ == '__main__':
    src = r'/home/pi/Pictures/img20210417_12203672.bmp'
    image0 = cv2.imread(src)
    seal_rm = SealRemove()
    image_0 = seal_rm.remove_red_seal(image0)
    # image_0_1 = cv2.cvtColor(image_0, cv2.COLOR_BGR2GRAY)

    image1 = cv2.imread(src, 0)
    image_1 = seal_rm.shijuanqingli(image1)
    image_result = seal_rm.join_image(image_0, image_1)

    cv2.imshow('new image', image_result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    src_temp = src.split(r'.')
    src_result = src_temp[0] + '_new.' + src_temp[1]

    cv2.imwrite(src_result,image_result)

处理后的图片如下。(处理前的图片有小朋友的答案在上面了,就不发了)

 

 

你可能感兴趣的:(去除红色,opencv,小学试卷,opencv)