首页 > 解决方案 > 使用 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 可以检测到的图像处理。
请帮助是否有任何工作来检测雕刻

看到堆栈溢出链接,但没有得到正确的想法

标签: pythonopencvimage-processingpython-tesseract

解决方案


请注意:这只是一个入门代码。你可以玩弄它,它还涉及很多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()

原图:

在此处输入图像描述

阈值图像:

在此处输入图像描述

中值模糊图像:

在此处输入图像描述

最终输出:

在此处输入图像描述

您可能想要尝试的其他一些形态学操作是DilationErosionOpeningClosing操作。文档可以在这里找到。


推荐阅读