c++ - 如何使用 C++ 从 OpenCV 中的框架中删除黑色边框?

标签 c++ image opencv crop

我想知道如何使用C++去除OpenCV中以下帧的黑色边框

Original Image

Result

任何帮助将不胜感激。

最佳答案

为了消除一些非黑噪声,我建议使用 cv::threshold 和形态学闭合。然后,您可以删除包含(例如)超过 5% 非黑色像素的行和列。

我尝试了以下代码,它适用于您的示例:

int main()
{
  const int threshVal = 20;
  const float borderThresh = 0.05f; // 5%

  cv::Mat img = cv::imread("img.jpg", cv::IMREAD_GRAYSCALE);
  cv::Mat thresholded;
  cv::threshold(img, thresholded, threshVal, 255, cv::THRESH_BINARY);
  cv::morphologyEx(thresholded, thresholded, cv::MORPH_CLOSE,
    cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)),
    cv::Point(-1, -1), 2, cv::BORDER_CONSTANT, cv::Scalar(0));

  cv::imshow("thresholded", thresholded);

  cv::Point tl, br;

  for (int row = 0; row < thresholded.rows; row++)
  {
    if (cv::countNonZero(thresholded.row(row)) > borderThresh * thresholded.cols)
    {
      tl.y = row;
      break;
    }
  }

  for (int col = 0; col < thresholded.cols; col++)
  {
    if (cv::countNonZero(thresholded.col(col)) > borderThresh * thresholded.rows)
    {
      tl.x = col;
      break;
    }
  }

  for (int row = thresholded.rows - 1; row >= 0; row--)
  {
    if (cv::countNonZero(thresholded.row(row)) > borderThresh * thresholded.cols)
    {
      br.y = row;
      break;
    }
  }

  for (int col = thresholded.cols - 1; col >= 0; col--)
  {
    if (cv::countNonZero(thresholded.col(col)) > borderThresh * thresholded.rows)
    {
      br.x = col;
      break;
    }
  }

  cv::Rect roi(tl, br);
  cv::Mat cropped = img(roi);

  cv::imwrite("cropped.jpg", cropped);

  return 0;
}

请注意,为了在所有样本上获得最佳结果,您可能需要调整一些参数:threshValborderThresh

您可能还想阅读有关 thresholding 的优秀教程和 morphology transformations .

关于c++ - 如何使用 C++ 从 OpenCV 中的框架中删除黑色边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34921761/

相关文章:

c++ - 在 Windows 上安装最新版本的 mingw-w64

C++ STL "Association Set/Map"

c++ - int&a 和 int &a 有区别吗?

c++ - Windows C++ CMD窗口切换

c++ - 使用冲浪描述符+弗兰匹配器的静态手势识别

c++ - boost 线程中的 "too few arguments to function"

Javascript for 循环使用图像数组作为敌人

javascript - 在文件对话框 AJAX 和 PHP 中选择后立即上传图像

java - 如何给html img src 的绝对路径?

python - 检测闭合轮廓