python - 使用 python 对药片进行刻印检测
问题描述
import cv2
import pytesseract
from PIL import Image
import numpy as np
# import bm3d
img = cv2.imread('1_2_2.png')
# img = cv2.medianBlur(img, 5)
img = cv2.GaussianBlur(img,(13,13),0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# gray = cv2.medianBlur(, 5)
# cv2.imshow("img", gray)
# gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY |
cv2.THRESH_OTSU)
[1]
v = np.median(gray)
sigma = 0.33
#---- apply automatic Canny edge detection using the computed median--
--
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
gray = cv2.Canny(img,lower,upper)
# ret,gray = cv2.threshold(gray,110,255,cv2.THRESH_BINARY)
kernel = np.ones((4,4),np.uint8)
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
gray = cv2.dilate(gray,kernel,iterations = 1)
# gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)\
# gray = cv2.erode(gray,kernel,iterations = 1)
gray = cv2.bitwise_not(gray)
cv2.imshow("threshold", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
# gray = cv2.medianBlur(gray, 3)
text = pytesseract.image_to_string(gray)
print(text)
我正在尝试代码中提到的一些图像处理,但无法获得 pytesseract 可以检测到的图像处理。
请帮助是否有任何工作来检测雕刻
解决方案
请注意:这只是一个入门代码。你可以玩弄它,它还涉及很多threshold
值,你需要尝试。当然,这不是最好的代码,但您可以将其作为起点。
我将简要概述以下步骤,并提供python
之后的代码以及output
它在每个步骤中生成的代码。
- 以灰度加载图像
- 使用较大的
kernel size
. 执行Adaptive Threshold而不是一些Global Threshold很重要,因为它考虑了相邻强度,这在您提供的示例图像中起着重要作用。 - 执行中值模糊以消除椒盐噪声。
- 找到面积相当大 的连通分量,并从最终图像中去除小岛噪声。
- 将最终轮廓绘制到输出图像中。
下面python
提供了实现此目的的代码:
import cv2
import numpy as np
image = cv2.imread('test.png')
output = np.zeros((image.shape[0],image.shape[1],3), np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C , cv2.THRESH_BINARY, 11, 1)
median = cv2.medianBlur(threshold, 11)
median = cv2.bitwise_not(median)
im2, contours, hierarchy = cv2.findContours(median,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
saved_cont = []
thresh = 100
for contour in contours:
if cv2.contourArea(contour) > thresh:
print(cv2.contourArea(contour))
saved_cont.append(contour)
cv2.drawContours(output, saved_cont,-1,(255,255,255),1)
cv2.imshow('original', gray)
cv2.imshow('threshold', threshold)
cv2.imshow('median', median)
cv2.imshow('contour', output)
cv2.imwrite("threshold.png", threshold)
cv2.imwrite("median.png", median)
cv2.imwrite("output.png", output)
cv2.waitKey(0)
cv2.destroyAllWindows()
原图:
阈值图像:
中值模糊图像:
最终输出:
您可能想要尝试的其他一些形态学操作是Dilation、Erosion、Opening和Closing操作。文档可以在这里找到。
推荐阅读
- batch-file - 如何使用 Windows 批处理文件有效地将大量数据写入大型文本文件
- python - 标准库中等待对象的 Python 列表
- java - Java 的 ListenableFuture 和 addListener 回调的单元测试
- python - 将 str.replace 用于列表列表
- javascript - 预检响应中的 Access-Control-Allow-Headers 不允许 XMLHttpRequest 请求标头字段 postman-token
- objective-c - 本地框架的更改未在我的项目中更新
- java - 如何维护用户登录会话?
- javascript - 如何在画布上实现波浪动画?使用延迟或其他技术
- node.js - How do I protect a node.js app using the saml2-js package?
- sitecore9 - 根级别的数据无效。第 1 行,sitecore 上的位置 1 升级到 9.2