我正在尝试使用OpenCV库识别手写数学运算符=
,但是,我遇到了一个问题,即它只能识别可以一键绘制的内容。
import cv2
import numpy as np
from PIL import Image, ImageOps
img = cv2.imread("sum.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Gaussian Blurring to reduce noise
blur = cv2.GaussianBlur(gray, (5,5), 0)
#Adaptive Thresholding to account for different light/shadows
threshed = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
morphed = cv2.morphologyEx(threshed, cv2.MORPH_OPEN, np.ones((3,3)))
conturs_lst = cv2.findContours(morphed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
for cnt in conturs_lst:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 255), 1, cv2.LINE_AA)
此代码导致这种行为,等号的两个部分被限制在单独的框中。
实际输出:
有人知道如何修改我的代码以使整个等号位于一个边界框之内吗?
答案 0 :(得分:0)
您可以尝试以下操作:
cv::namedWindow("result1", cv::WINDOW_FREERATIO);
cv::namedWindow("result2", cv::WINDOW_FREERATIO);
cv::Mat img = cv::imread(R"(FRfLi.png)");
// to gray
cv::Mat gray;
cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
cv::threshold(gray, gray, 80, 255, cv::THRESH_BINARY_INV);
cv::morphologyEx(gray, gray, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 27)));
cv::imshow("result1", gray);
std::vector<std::vector<cv::Point> > contours;
cv::findContours(gray, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (int i = 0; i < contours.size(); ++i) {
cv::Rect rect = cv::boundingRect(contours[i]);
rect.x -= 3;
rect.y -= 3;
rect.width += 6;
rect.height += 6;
cv::rectangle(img, rect, cv::Scalar(0, 0, 255), 2);
}
cv::imshow("result2", img);
cv::waitKey();
变形后,您将得到以下结果:
检测轮廓,您将得到以下结果:
注意: 该代码为C ++,您可以考虑实现该代码的步骤。
希望它能对您有所帮助!