使用 C++ (OpenCV) 删除所有黑色像素并仅获取所需图像

remove all black pixels and get only required image using C++ (OpenCV)

我已经尝试使用 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 进行包装。

对于灰度图像,以下代码可以完美运行。

值 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

或者,实际执行 trim:

convert thing.jpg -threshold 50% -trim result.jpg

关键字: 图像处理, OpenCV, C++, trim, trim box, trim-box, crop, crop-box , 边框, 边框, 移除边框, trim 边框, ROI, boundingRect(), cv::boundingRect()