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:
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
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()
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With