我是OpenCV的新手,我想写一张有倾斜文本的图片。我首先读取GrayScale中的图像并对其进行二进制化,然后尝试执行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)
中获取顶点。请帮帮我!
发布于 2016-09-20 04:30:13
也许你可以看看这个:http://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
在该链接中,作者遍历或转换整个文档(以及包含的文本),但是,这取决于根据图像中的轮廓找到文档的边缘。
他在下面的教程中进一步介绍了这个问题:http://www.pyimagesearch.com/2014/09/01/build-kick-ass-mobile-document-scanner-just-5-minutes/
他的解决方案之所以有效,是因为他可以根据检测到的文档的位置、方向和偏斜程度来调整整个文档。实际上,调整整个文档的位置将调整文档中的所有内容,包括文本。
然而,我相信您所要求的是,即使没有检测到任何文档边缘和轮廓,您也希望对文本进行遍历。如果是这样的话,那么我假设您需要提供另一个基础或标准来建立文本分解(即检测图像中有字母,然后根据您的标准检测字母有多偏斜,然后调整字母),这可能是一项重要的练习。
https://stackoverflow.com/questions/39585407
复制相似问题