python - 如何在数字所在的确切位置裁剪图像?

标签 python numpy opencv image-recognition python-tesseract

我有我的代码原型(prototype):

import cv2
import numpy as np

img = cv2.imread('/home/follia/Pictures/scan.jpg')

h, w, k = img.shape
M = cv2.getRotationMatrix2D((w / 2, h / 2), 15.5, 1)
img = cv2.warpAffine(img, M, (w, h))

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200, apertureSize=3)

lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 80)
for x in range(0, len(lines)):
    for x1,y1,x2,y2 in lines[x]:
        cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imshow("origin", img)
cv2.waitKey(0)

原图: enter image description here 它返回这个图像: image I get

我需要裁剪此图像并仅显示数字: image I need

你能帮我一下吗,我该如何剪切这个位置? 然后,我如何识别数字并将其从图像提取到文本?

最佳答案

试试这个:

该解决方案的基本思想是,执行threshold()后获取图像的轮廓,并检测轮廓中最大的轮廓。

输入:

代码:

import cv2
image = cv2.imread("test.jpg", 1)
h, w, k = image.shape
M = cv2.getRotationMatrix2D((w / 2, h / 2), 15.5, 1)
image = cv2.warpAffine(image, M, (w, h), cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))

img = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
threshold = 80
cv2.threshold(img,threshold,255,cv2.THRESH_BINARY,img)
cv2.bitwise_not(img,img)
cv2.imshow("Result", img)
cv2.waitKey(0)
im2, contours, hier = cv2.findContours(img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    #find the biggest area
    c = max(contours, key = cv2.contourArea)
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
    crop_img = image[y:y + h, x:x + w]
    cv2.imshow("Result", crop_img)
    cv2.waitKey(0)

cv2.imshow("Result", image)
cv2.waitKey(0)

输出:

关于python - 如何在数字所在的确切位置裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807370/

相关文章:

python - 组合两个不同数据帧的向量化 for 循环

python - 如何使用 pyramid.response.FileIter

python - 用NumPy填充图像会全黑

python - 我可以使用 lambdify 来评估 python 函数的导数吗?

java - 如何在Java中使用group by聚合CSV数据?

c++ - 在OpenCV中,DescriptorExtractor类的descriptorType()返回什么?

python - 预测事件顺序的机器学习算法?

python - 如何使用 MongoDB 高效地将数据从一个集合聚合到另一个集合中?

python - 如何按 NAN 值拆分 Pandas 时间序列

python - opencv python中的渐变蒙版混合