我尝试了findNonZero和boundingRect。但是没有任何帮助。 我是C ++ OpenCV的新手。我使用涉及NumPy的Python OpenCV进行了此操作,但不幸的是,我无法在C ++中执行相同的操作。
输入图片
Python:
def crop_with_arg(refactor_image):
mask = refactor_image > 0
coord = np.argwhere(mask)
x0, y0 = coord.min(axis=0)
x1, y1 = coord.max(axis=0) + 1
cropped = refactor_image[x0:x1, y0:y1]
return cropped
def crop_image(image_crop, tol=50):
mask = image_crop > tol
return image_crop[np.ix_(mask.any(1), mask.any(0))]
compressed_img = crop_with_arg(gray)
croppped_image = crop_image(compressed_img, tol=50)
我正在用Objective C ++编写代码以具有iOS的包装器。
答案 0 :(得分:1)
对于灰度图像,以下代码可以正常工作。
值50是可以基于完成的预处理设置的阈值限制。
grayThres = gray > 50;
graycloned = grayThres.clone();
std::vector<cv::Point> nonBlackList;
nonBlackList.reserve(graycloned.rows*graycloned.cols);
for(int j=0; j<graycloned.rows; ++j)
for(int i=0; i<graycloned.cols; ++i)
{
// if not black: add to the list
if(graycloned.at<cv::Vec2b>(j,i) != cv::Vec2b(0,0))
{
nonBlackList.push_back(cv::Point(j,i));
}
}
// create bounding rect around those points
cv::Rect bb = cv::boundingRect(nonBlackList);
cv:: Mat returnImage = gray(bb);
答案 1 :(得分:0)
我认为使用cv::boundingRect()
这样的事情会非常有效:
#include <iostream>
#include <opencv2/opencv.hpp>
int
main(int argc,char*argv[])
{
// Load image as greyscale
cv::Mat im = cv::imread("thing.jpg", cv::IMREAD_GRAYSCALE);
// Threshold image at 128
cv::Mat thresh;
cv::threshold(im, thresh, 128, 255, cv::THRESH_BINARY);
// Do the actual work
double t = (double)cv::getTickCount();
cv::Rect ROI = cv::boundingRect(thresh);
t = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
// Print timing and results
std::cout << "Time: " << t*1000.0 << "ms" << std::endl;
std::cout << ROI << std::endl;
}
示例输出
Time: 0.317279ms
[253 x 48 from (113, 503)]
顺便说一句,您可以使用 ImageMagick 从命令行更轻松地完成此操作,该软件包包含在大多数Linux发行版中,并且可用于macOS和Linux:
# Print coordinates of trim-box
convert thing.jpg -threshold 50% -format %@ info:
253x48+113+503
或者,实际上进行修剪:
convert thing.jpg -threshold 50% -trim result.jpg
关键字:图像处理,OpenCV,C ++,修剪,修剪框,修剪框,修剪,修剪框,边框,边框,删除边框,修剪边框,ROI,boundingRect(), cv :: boundingRect()