去除印章 ----python

Como0413發表於2019-03-12
#-*- coding: utf-8 -*-

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

class Image:
    def __init__(self,filename):
        self.filename = filename
        self.image = None
        self.Bch = None
        self.Gch = None
        self.Rch = None
        return
    def load(self):
        self.image = cv.imread(self.filename,cv.IMREAD_ANYCOLOR)
        row, col, _ = self.image.shape
        ratio = 1
        if row/320 > 1.0:
            ratio = float(320/row)
        cv.resize(self.image,(int(ratio*row),int(ratio*col)))
        return

    def HSV_img(self):
        hsv = cv.cvtColor(self.image,cv.COLOR_BGR2HSV)
        #顏色的HSV值,比如要提取圖中紅色
        blow = np.array([156, 43, 46])
        btop = np.array([180, 255, 255])
        mask = cv.inRange(hsv, blow, btop)
        out = cv.bitwise_and(self.image,hsv,mask=mask)
        cv.imshow('out',out)
        cv.waitKey(500)
        return

    # 獲取三通道
    def BGR_img(self):
        #獲取三通道
        self.Bch, self.Gch, self.Rch = cv.split(self.image)
        cv.imshow('Rch',self.Rch)
        cv.waitKey(500)
        return

    def HIST_img(self):
        # 降維
        red = self.Rch.flatten()
        plt.figure()
        histogram,bins,patch=plt.hist(red, 256, facecolor='cyan',  histtype='bar')     # facecolor設定為黑色
        maxIndex = np.argsort(histogram)[:-1]
        j = 0
        for i in range(len(maxIndex) - 1):
            k = maxIndex[i+1]
            #70可調,是根據影像來調節的
            if maxIndex[i] - k > 70:
                j = k

        res, thresh = cv.threshold(self.Rch, j, 255, cv.THRESH_BINARY)
        kernel = np.ones((3, 3), np.uint8)
        # 腐蝕
        erosion = cv.erode(thresh, kernel=kernel, iterations=1)
        # 膨脹
        dilation = cv.dilate(thresh, kernel, iterations=1)
        cv.imshow('thresh',thresh)
        cv.imshow('erosion',erosion)
        cv.imshow('dilation', dilation)
        cv.waitKey(500)
        plt.show()

    def run(self):
        self.load()
        self.HSV_img()
        self.BGR_img()
        self.HIST_img()

I = Image(影像地址)
I.run()

 

相關文章