【发布时间】:2016-09-20 03:50:58
【问题描述】:
我是 OpenCV 的新手,我想对具有倾斜文本的图像进行纠偏。首先我用灰度读取图像并对其进行二值化,然后我尝试做this:
import cv2
import numpy as np
img = cv2.imread('m20.jpg',0)
ret,byw = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
_, contours, hierarchy = cv2.findContours(byw.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
draw = cv2.cvtColor(byw, cv2.COLOR_GRAY2BGR)
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(draw, [box], 0, (0, 255, 0), 2)
但不起作用,因为 findContours() 期望接收具有身体形状的图像。 我尝试的其他方法是翻译这段 c++ 代码:
// Read image
Mat3b img = imread("path_to_image");
// Binarize image. Text is white, background is black
Mat1b bin;
cvtColor(img, bin, COLOR_BGR2GRAY);
bin = bin < 200;
// Find all white pixels
vector<Point> pts;
findNonZero(bin, pts);
// Get rotated rect of white pixels
RotatedRect box = minAreaRect(pts);
if (box.size.width > box.size.height)
{
swap(box.size.width, box.size.height);
box.angle += 90.f;
}
Point2f vertices[4];
box.points(vertices);
for (int i = 0; i < 4; ++i)
{
line(img, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0));
}
// Rotate the image according to the found angle
Mat1b rotated;
Mat M = getRotationMatrix2D(box.center, box.angle, 1.0);
warpAffine(bin, rotated, M, bin.size());
我有这个:
draw = cv2.cvtColor(byw, cv2.COLOR_GRAY2BGR)
data = np.array(byw)
subzero = np.nonzero(data)
subuno = np.reshape(subzero,(17345,2)) # this is because cv2.minAreaRect() receives a Nx2 numpy
rect = cv2.minAreaRect(subuno)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(draw,[box],0,(0,255,0),2)
但是结果又不是预期的,矩形没有很好地定位。
我也想到可能会尝试使
for 像在 C++ 中一样,但我不知道如何从
box = cv2.boxPoints(rect)。请帮忙!
【问题讨论】:
-
问一个明确的问题
标签: python c++ opencv vertices skew