使用Python去掉試卷上的藍色和紅色筆記

# -*- 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.5)

        _, red_thresh = cv2.threshold(red_c, filter_condition, 255, cv2.THRESH_BINARY)

        # 把圖片轉回 3 通道
        result_img = np.expand_dims(red_thresh, axis=2)
        result_img = np.concatenate((result_img, result_img, result_img), axis=-1)

        return result_img

    def remove_blue_seal(self, image):
        """
        去除紅色印章
        """

        # 獲得紅色通道
        blue_c, green_c, red_c = cv2.split(image)

        # 多傳入一個參數cv2.THRESH_OTSU,並且把閾值thresh設爲0,算法會找到最優閾值
        thresh, ret = cv2.threshold(blue_c, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        # 實測調整爲95%效果好一些
        filter_condition = int(thresh * 0.2)

        _, red_thresh = cv2.threshold(blue_c, filter_condition, 255, cv2.THRESH_BINARY)

        # 把圖片轉回 3 通道
        result_img = np.expand_dims(red_thresh, axis=2)
        result_img = np.concatenate((result_img, result_img, result_img), axis=-1)

        return result_img

    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__':
    image = r'C:\Users\keying\Desktop\math\2.jpg'
    img = cv2.imread(image)
    seal_rm = SealRemove()
    rm_img1 = seal_rm.remove_red_seal(img)
    rm_img2 = seal_rm.remove_blue_seal(img)
    rm_img = seal_rm.join_image(rm_img1,rm_img2)
    cv2.imwrite(r"C:\Users\keying\Desktop\math\2.new.jpg", rm_img)

  

 

參考:

https://blog.csdn.net/sogobaidu/article/details/115829791

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章