Ant*_*ony 6 python opencv image-processing computer-vision
我有这样的示例图像
我正在寻找一种方法来消除图像中的噪音,这样我最终得到的图像在白色背景上只有黑色文字,这样我就可以将它发送到tesseract.
我试过变形了
kernel = np.ones((4,4),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imshow("opening", opening)
Run Code Online (Sandbox Code Playgroud)
但它似乎没有用.
我也试图找到轮廓
img = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)
(cnts, _) = cv2.findContours(img, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
roi=rotated[y:y+h,x:x+w].copy()
cv2.imwrite("roi.png", roi)
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,我得到以下轮廓:
裁剪时会导致此图像:
这还不够好.我想要在白色背景上的黑色文字,以便我可以将它发送到tesseract OCR并具有良好的成功率.
还有什么我可以尝试的吗?
更新
这是一个额外的类似图像.这个有点容易,因为它有一个光滑的矩形
以下内容适用于您给定的示例,尽管可能需要针对更广泛的图像进行调整。
import numpy as np
import cv2
image_src = cv2.imread("input.png")
gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 250,255,0)
image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
largest_area = sorted(contours, key=cv2.contourArea)[-1]
mask = np.zeros(image_src.shape, np.uint8)
cv2.drawContours(mask, [largest_area], 0, (255,255,255,255), -1)
dst = cv2.bitwise_and(image_src, mask)
mask = 255 - mask
roi = cv2.add(dst, mask)
roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(roi_gray, 250,255,0)
image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
max_x = 0
max_y = 0
min_x = image_src.shape[1]
min_y = image_src.shape[0]
for c in contours:
if 150 < cv2.contourArea(c) < 100000:
x, y, w, h = cv2.boundingRect(c)
min_x = min(x, min_x)
min_y = min(y, min_y)
max_x = max(x+w, max_x)
max_y = max(y+h, max_y)
roi = roi[min_y:max_y, min_x:max_x]
cv2.imwrite("roi.png", roi)
Run Code Online (Sandbox Code Playgroud)
为您提供以下类型的输出图像:
和...
该代码的工作原理是首先找到最大的轮廓区域。由此创建一个蒙版,用于首先仅选择内部区域,即文本。然后将遮罩的反面添加到图像中,将遮罩外部的区域转换为白色。
最后再次找到这个新图像的轮廓。任何超出合适尺寸范围的轮廓区域都将被丢弃(这用于忽略任何小噪声区域),并为每个轮廓找到一个边界矩形。对于每个矩形,outer计算所有剩余轮廓的边界矩形,并使用这些值进行裁剪以给出最终图像。
更新- 要获取图像的其余部分,即删除上述区域,可以使用以下内容:
image_src = cv2.imread("input.png")
gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 10, 255,0)
image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
largest_area = sorted(contours, key=cv2.contourArea)[-1]
mask = np.zeros(image_src.shape, np.uint8)
cv2.drawContours(mask, [largest_area], 0, (255,255,255,255), -1)
image_remainder = cv2.bitwise_and(image_src, 255 - mask)
cv2.imwrite("remainder.png", image_remainder)
Run Code Online (Sandbox Code Playgroud)