检测图片上的红色印章

import os
import cv2
import numpy as np
import tensorflow as tf
import sys

detection_graph = tf.Graph()
model_file = "./tag_detect/finger_stamp.pb"
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(model_file, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config, graph=detection_graph)

image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')



def red_check(cropped):
    h,s,v = cv2.split(cv2.cvtColor(cropped,cv2.COLOR_BGR2HSV))

    h_min_0 = 0
    h_max_0 = 10

    h_min_1 = 156
    h_max_1 = 180

    s_min = 43
    s_max = 255

    v_min = 46
    v_max = 255

    h_0 = cv2.inRange(h,h_min_0 , h_max_0)
    h_1 = cv2.inRange(h,h_min_1 , h_max_1)
    s_ = cv2.inRange(s,s_min, s_max)
    v_= cv2.inRange(v,v_min, v_max)
    h_ = cv2.bitwise_or(h_0,h_1)
    all_ = h_&s_&v_
    red_ratio = (all_ == 255).sum()/float(cropped.shape[0]*cropped.shape[1])
    #print(all_.shape)
    #print(type(all_))
    #print(all_.dtype)
    #print('red_check' ,red_ratio)
    if red_ratio>0.02:
        return u"是"
    return u"否"


def get(image, thresh = 0.5):
    h,w,c = image.shape
    res = {"finger":u"否", "stamp":u"否", "sign":u"否"}

    resized_dp = 960.0/h
    image_resized = cv2.resize(image,None,fx = resized_dp, fy = resized_dp)
    image = cv2.cvtColor(image_resized,cv2.COLOR_BGR2RGB)
    image_expanded = np.expand_dims(image, axis=0)
    out = sess.run([num_detections,detection_scores,detection_boxes,detection_classes],
        feed_dict={image_tensor: image_expanded})
    num = int(out[0][0])
    rows,cols,_= image.shape

    for i in range(num):
        classId = int(out[3][0][i])
        score = float(out[1][0][i])
        bbox = [float(v) for v in out[2][0][i]]
        if score > thresh:
            x = int(bbox[1] * cols)
            y = int(bbox[0] * rows)
            right = int(bbox[3] * cols)
            bottom = int(bbox[2] * rows)
            cropped = image_resized[y:bottom,x:right]
            
            if classId == 1:
                if res['finger'] == u"是":
                    continue
                res['finger'] = red_check(cropped) 
                res['sign'] = res['finger']
                continue

            elif classId == 2:
                if res['stamp'] == u"是":
                    continue
                res['stamp'] = red_check(cropped)
                continue

    return res 


if __name__ == "__main__":
    image = cv2.imread(sys.argv[1])
    image_expanded = np.expand_dims(image, axis=0)
    ret = get(image)
    print(ret)

 

在OpenCV中,去除红色印章通常涉及到颜色空间转换和图像处理技术,特别是使用色彩空间分离和边缘检测。以下是一个基本步骤的概述: 1. **色彩空间转换**:将图像从BGR(OpenCV默认)转换到HSV或HLS颜色空间,因为印章通常在特定的颜色范围内,如红色。 ```python import cv2 img = cv2.imread('image.jpg') hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) ``` 2. **设置红色阈值**:根据印章的颜色选择合适的HSV范围,比如红色印章大约在(0, 100, 100)至(10, 255, 255)之间。你可以使用`cv2.inRange()`函数创建一个红色掩码。 ```python lower_red = (0, 50, 50) upper_red = (10, 255, 255) mask = cv2.inRange(hsv_img, lower_red, upper_red) ``` 3. **腐蚀与膨胀**:为了消除边缘的噪声,可以对红色掩码应用腐蚀和膨胀操作。 ```python kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) ``` 4. **图像减法**:用原图像减去红色掩模,得到去除印章后的图像。 ```python result = cv2.bitwise_and(img, img, mask=mask) ``` 5. **可能的后期处理**:如果结果仍有残留,可以尝试使用形态学操作、边缘检测或者机器学习算法进一步优化。 ```python # 可能的后续操作... edges = cv2.Canny(result, threshold1, threshold2) ``` **相关问题--:** 1. OpenCV中的哪些函数常用于图像颜色空间转换? 2. 在去除印章过程中,为什么要进行腐蚀和膨胀操作? 3. 除了颜色阈值,还有哪些方法可以用来识别印章区域?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值