【发布时间】:2017-07-04 11:45:12
【问题描述】:
我想使用纠偏图像。为此,我编写了一个程序(诚然有很多帮助):
- 将图像转换为更易于计算(thresh、dilation 等)
- 围绕所有对象绘制轮廓
- 计算文本轮廓周围的四个极值点(忽略任何有边距的东西)
- 使用 cv2.minAreaRect 在该区域周围绘制一个矩形
这个想法是 cv2.minAreaRect 也返回角度,我可以用它来歪斜图像。但是,就我而言,它是 –90°。
我在“干净”的图像上测试了程序(MS Word 屏幕截图在 Gimp 中旋转 ≈ 30°),得到了相同的结果。
我的代码:
import numpy as np
import cv2
import itertools
img = cv2.imread('zuo.png')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,64,255,0)
############
kernel = np.ones((2,2),np.uint8)
img_e = cv2.dilate(thresh,kernel,iterations = 1)
# cv2.imwrite("out_eroded.png", img_e)
# http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html
# img_e = thresh
############
imgbw, contours, hierarchy = cv2.findContours(img_e,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# imgbw, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
margin_distance = 25
def flatten(arr, n = 1):
# print(arr)
ret = list(itertools.chain.from_iterable(arr))
# print(ret)
if n != 1:
return flatten(ret, n - 1)
else:
return ret
# print(list(flatten([[1,2,3],[4,5,6], [7], [8,9]])))
def get_min_max_values(cs, im_y, im_x):
# print(flatten(cs), 1)
# print(im_y, im_x)
min_y = im_y - margin_distance
min_x = im_x - margin_distance
max_y = margin_distance
max_x = margin_distance
for lvl1 in cs:
for lvl2 in lvl1:
x, y = lvl2[0]
# x = im_x - x
# y = im_y - y
max_y = max(y, max_y) if y + margin_distance < im_y else max_y
max_x = max(x, max_x) if x + margin_distance < im_x else max_x
min_y = min(y, min_y) if y > margin_distance else min_y
min_x = min(x, min_x) if x > margin_distance else min_x
return ((min_y, min_x), (min_y, max_x), (max_y, min_x), (max_y, max_x))
new_rect = get_min_max_values(contours, len(img), len(img[0]))
new_rect = list(map(lambda x: list(x)[::-1], list(new_rect)))
print(new_rect)
rect = cv2.minAreaRect(np.int0(new_rect))
# print(rect)
print(rect)
box = cv2.boxPoints(rect)
box = np.int0(box)
img_out = cv2.drawContours(img, [box], -1, (0,0,255), 5) # -1 = wszystkie kontury
img_out = cv2.drawContours(img, contours, -1, (0,255,0), 3)
cv2.imwrite("out.png", img_out)
为什么矩形没有倾斜以匹配文本?我没有看到任何可以证明这一点的人工制品。
【问题讨论】:
-
你能画出
new_rect中包含的点(用红色圆圈或其他什么)吗? -
您也可以添加 GIMP 图像和结果吗?
-
在 get_min_max_values 中返回一个轴对齐的矩形(角点),这就是 minAreaRect 优化的内容。
-
@Miki 你的意思是生成一个形状并使用这些坐标在原始文件上绘制它吗?
-
我的意思是你最好画出这些点(在你的图像上使用“圆圈”),因为它们可能是错误的,正如 Micka 所说的
标签: python image python-3.x opencv image-processing