我编写了一个简单的代码来搜索文档中的圆(因为印章是圆形的).

但由于图像质量差,打印轮廓模糊,opencv无法始终检测到它.我在photoshop中编辑了这张图片,并增强了深色.我保存了这张照片并将其发送处理.它帮助了我.Opencv发现了一个代表低质量打印的圆圈(高质量文档中不存在此类问题).我的代码:

import numpy as np
import cv2

img = cv2.imread(r"C:\buh\doc.jpg")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


# I tried experimenting with bluer, but opencv doesn't see circles in this case
# blurred = cv2.bilateralFilter(gray.copy(), 15, 15, 15 )
# imS = cv2.resize(blurred, (960, 540))
# cv2.imshow('img', imS)
# cv2.waitKey(0)



minDist = 100
param1 = 30 #500
param2 = 100 #200 #smaller value-> more false circles
minRadius = 90
maxRadius = 200 #10

# docstring of HoughCircles: HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius)

if circles is not None:
    circles = np.uint16(np.around(circles))
    for i in circles[0, :]:
        cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)

# Show result for testing:
imS = cv2.resize(img, (960, 540))
cv2.imshow('img', imS)
cv2.waitKey(0)

文件中的印章为圆形,如图所示:

enter image description here

不幸的是,我不能添加原始印章所在文件的照片,因为这是一个私有信息...

所以,在try 寻找圆圈之前,我需要增强照片中的黑色色调.我该怎么做?如果有人已经遇到过这种情况,我还会听取其他关于改进印章轮廓的建议.

非常感谢.

例子:

enter image description here

推荐答案

这里有一个简单的方法:

  1. Obtain binary image.加载图像,转换为grayscaleGaussian blur,然后是Otsu's threshold.

  2. Merge small contours into a single large contour.我们用cv2.dilate放大,把圆合并成一个轮廓.

  3. Find external contours.最后我们使用外部cv2.RETR_EXTERNAL标志和cv2.drawContours()


图像管道的可视化

输入图像

二值图像的阈值

扩张

检测到的绿色轮廓

密码

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Otsus threshold, dilate
image = cv2.imread('3.PNG')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
dilate = cv2.dilate(thresh, kernel, iterations=1)

# Find contours
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), 3)

cv2.imshow('image', image)
cv2.imshow('dilate', dilate)
cv2.imshow('thresh', thresh)
cv2.waitKey()     

Python相关问答推荐

如何计算部分聚合数据的统计数据

Python中两个矩阵的自定义Hadamard风格产物

在Transformer中使用LabelEncoding的ML模型管道

如何在Python中增量更新DF

将行从一个DF添加到另一个DF

Image Font生成带有条形码Code 128的条形码时出现枕头错误OSErsor:无法打开资源

Python在tuple上操作不会通过整个单词匹配

try 与gemini-pro进行多轮聊天时出错

根据不同列的值在收件箱中移动数据

Django mysql图标不适用于小 case

如何记录脚本输出

如果值不存在,列表理解返回列表

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

在Python中动态计算范围

如何将多进程池声明为变量并将其导入到另一个Python文件

Scrapy和Great Expectations(great_expectations)—不合作

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

python sklearn ValueError:使用序列设置数组元素

如何在Python请求中组合多个适配器?