C ++ opencv code tutorial for converting a blue background photo into a white background photo, opencv code
C ++ opencv code tutorial for converting a blue background photo into a white background photo.
# Include <opencv2/opencv. hpp> # include <opencv2/core. hpp> # include <opencv2/highgui. hpp> # include <opencv2/imgproc. hpp> using namespace std; using namespace cv; // contains the cv namespace int main () {char * origin = "Original"; char * window = "Image "; char * str = "G: \ yay.jpg"; namedWindow (origin, 1); namedWindow (window, 1); Mat image = imread (str); if (! Image. data) {cout <"image loading problems" <endl; return 0;} Mat roi = image (Rect (20, 20, 20); Mat hsvImg; cvtColor (image, hsvImg, CV_BGR2HSV); // convert the image to HSV Color Space // separate the HSV space, v [0] is H-tone, v [1] is S saturation, v [2] is a v grayscale vector <Mat> v; split (hsvImg, v); Mat roiH = v [0] (Rect (20, 20, 20 )); mat roiS = v [1] (Rect (20, 20, 20); int SumH = 0; int SumS = 0; int avgH, avgS; // average color and average saturation of the blue background // calculate the average color and average saturation of a blue background (int I = 0; I <20; I ++) {for (int J = 0; j <20; j ++) {/* SumH = SumH + roiH (I, j); */SumH = int (roiH. at <uchar> (j, I) + SumH; SumS = int (roiS. at <uchar> (j, I) + SumS ;}} avgH = SumH/400; avgS = SumS/400; // traverse the entire image int nl = hsvImg. rows; int nc = hsvImg. cols; int step = 10; for (int j = 0; j <nl; j ++) {for (int I = 0; I <nc; I ++) {// use H.S channels for threshold segmentation, and replace blue with red if (v [0]. at <uchar> (j, I) <= (avgH + 5) & v [0]. at <uchar> (j, I)> = (avgH-5) & (v [1]. at <uchar> (j, I) <= (avgS + 40) & v [1]. At <uchar> (j, I)> = (avgS-40) {// cout <int (v [0]. at <uchar> (j, I) <endl; // Red Bottom // v [0]. at <uchar> (j, I) = 0; // white v [0]. at <uchar> (j, I) = 0; v [1]. at <uchar> (j, I) = 0; // if the values of V [0] and V [1] are all set to 0, the result is white. // green bottom. // v [0]. at <uchar> (j, I) = 60; // blue bottom // v [0]. at <uchar> (j, I) = 120;/* cout <int (v [0]. at <uchar> (j, I) <endl; */} Mat finImg; merge (v, finImg); Mat rgbImg; cvtColor (finImg, rgbImg, cv_hsv 2bgr); // convert the image back to the RGB space imshow (origin, image ); Imshow (window, rgbImg); // Add a filter to filter out the value of the edge part (a low-pass filter should be used here, but it does not feel good, or it is unnecessary .) Mat result; GaussianBlur (rgbImg, result, Size (3, 3), 0.5); imshow (window, result); imwrite ("new.jpg", result); waitKey (0 ); // system ("pause"); return 0 ;}