在OpenCV C++中拼接2张图像后去除图像的黑色部分

Air*_*isa 4 c++ opencv image image-processing image-stitching

所以我在 OpenCV C++ 中拼接了 2 个图像,但我知道图像中有一个全黑的部分,想删除它。要走的路是什么?

这是我的图像输出:

在此处输入图片说明

nat*_*ncy 6

这个想法是对每列的像素求和,然后遍历数据以构建新图像。如果列的值为零,则表示它是黑色的,因此我们忽略它,否则我们将列 ROI 连接到最终图像。这是列像素的总和:

结果

在此处输入图片说明

我在 Python 中实现了它,但您可以将类似的想法应用到 C++

import cv2
import numpy as np 
# import matplotlib.pyplot as plt

# Load image, convert to grayscale, and sum column pixels
image = cv2.imread('1.jpg')
h, w = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
first_pass = True
pixels = np.sum(gray, axis=0).tolist()

# Build new image
for index, value in enumerate(pixels):
    if value == 0:
        continue
    else:
        ROI = image[0:h, index:index+1]
        if first_pass:
            result = image[0:h, index+1:index+2]
            first_pass = False
            continue
        result = np.concatenate((result, ROI), axis=1)

cv2.imshow('result', result)
cv2.imwrite('result.png', result)
# Uncomment for plot visualization
# plt.plot(pixels, color='teal')
# plt.show()
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)


Yun*_*enk 3

注意: 根据 nathancy 的回答,我刚刚使用 C++ 进行了编码:

#include <iostream>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("/your/image/directory/image.jpg");

    for(int i=0;i<img.cols;i++)
    {
        int black_cnt = 0;
      for(int j=0;j<img.rows;j++)
      {
         if(img.at<cv::Vec3b>(j,i)[0]==0)
             black_cnt++;
      }
      if(black_cnt==img.rows)
          continue;
      else
      {
          Rect roi(i,0,img.cols-i,img.rows);
          img = img(roi);
          break;
      }
    }    
    imshow("Result",img);        
    waitKey(0);        
    return 0;

}
Run Code Online (Sandbox Code Playgroud)