对于灰度图像,以下代码可以正常工作。
值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);
,
我认为使用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()
本文链接:https://www.f2er.com/3116931.html