1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <opencv2/opencv.hpp> #include <iostream>
using namespace std; using namespace cv;
int main(int argc, char** argv) { Mat src = imread("/Users/LeeWong/Downloads/photo_red.jpeg"); if (src.empty()) { printf("could not load image...\n"); return -1; } imshow("原圖", src);
// 1.將二維影象資料線性化 Mat data; for (int i = 0; i < src.rows; i++) //畫素點線性排列 for (int j = 0; j < src.cols; j++) { Vec3b point = src.at<Vec3b>(i, j); Mat tmp = (Mat_<float>(1, 3) << point[0], point[1], point[2]); data.push_back(tmp); }
// 2.使用K-means聚類;分離出背景色 int numCluster = 4; Mat labels; TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1); kmeans(data, numCluster, labels, criteria, 3, KMEANS_PP_CENTERS);
// 3.背景與人物二值化 Mat mask = Mat::zeros(src.size(), CV_8UC1); int index = src.rows * 2 + 2; //獲取點(2,2)作為背景色 int cindex = labels.at<int>(index); /* 提取背景特徵 */ for (int row = 0; row < src.rows; row++) { for (int col = 0; col < src.cols; col++) { index = row * src.cols + col; int label = labels.at<int>(index); if (label == cindex) { // 背景 mask.at<uchar>(row, col) = 0; } else { mask.at<uchar>(row, col) = 255; } } } //imshow("mask", mask);
// 4.腐蝕 + 高斯模糊:影象與背景交匯處高斯模糊化 Mat k = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1)); erode(mask, mask, k); //imshow("erode-mask", mask); GaussianBlur(mask, mask, Size(3, 3), 0, 0); //imshow("Blur Mask", mask);
// 5.更換背景色以及交匯處融合處理 RNG rng(12345); Vec3b color; //設定的背景色 color[0] = 255;//rng.uniform(0, 255); color[1] = 255;// rng.uniform(0, 255); color[2] = 255;// rng.uniform(0, 255); Mat result(src.size(), src.type());
double w = 0.0; //融合權重 int b = 0, g = 0, r = 0; int b1 = 0, g1 = 0, r1 = 0; int b2 = 0, g2 = 0, r2 = 0;
for (int row = 0; row < src.rows; row++) { for (int col = 0; col < src.cols; col++) { int m = mask.at<uchar>(row, col); if (m == 255) { result.at<Vec3b>(row, col) = src.at<Vec3b>(row, col); // 前景 } else if (m == 0) { result.at<Vec3b>(row, col) = color; // 背景 } else {/* 融合處理部分 */ w = m / 255.0; b1 = src.at<Vec3b>(row, col)[0]; g1 = src.at<Vec3b>(row, col)[1]; r1 = src.at<Vec3b>(row, col)[2];
b2 = color[0]; g2 = color[1]; r2 = color[2];
b = b1 * w + b2 * (1.0 - w); g = g1 * w + g2 * (1.0 - w); r = r1 * w + r2 * (1.0 - w);
result.at<Vec3b>(row, col)[0] = b; result.at<Vec3b>(row, col)[1] = g; result.at<Vec3b>(row, col)[2] = r; } } } imshow("背景替換", result);
waitKey(0); return 0; }
|