Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a black part of image after stitching 2 images in OpenCV C++

So I stitched 2 images in OpenCV C++ but I know have a full black part in the image and would like to remove it. What would be the way to go?

Here is my image output:

enter image description here

like image 300
AirKlisa Avatar asked Dec 22 '22 19:12

AirKlisa


2 Answers

The idea is to sum the pixels of each column then iterate through the data to construct the new image. If the value of a column is zero then it means it is black so we ignore it otherwise we concatenate the column ROI to the final image. Here's the summation of the column pixels:

Result

enter image description here

I implemented it in Python but you can adapt a similar idea to 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()
like image 144
nathancy Avatar answered Dec 26 '22 00:12

nathancy


Note: According to nathancy's answer I just coded using 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;

}
like image 39
Yunus Temurlenk Avatar answered Dec 25 '22 22:12

Yunus Temurlenk