opencv-009-色彩空间及其应用(提取图像的前景和背景)

知识点

  • RGB色彩空间

  • HSV色彩空间 -维基百科 ### 直方图算法中常用

  • YUV色彩空间

  • YCrCb色彩空间 # 皮肤检测常用

API知识点

  • 色彩空间转换cvtColor
  • 提取指定色彩范围区域inRange

代码(c++,python)

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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 色彩空间及其应用
*/
int main() {
Mat src = imread("../images/test.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// RGB ==> HSV YUV YCrCb
Mat hsv, yuv, ycrcb;
cvtColor(src, hsv, COLOR_BGR2HSV);
cvtColor(src, yuv, COLOR_BGR2YUV);
cvtColor(src, ycrcb, COLOR_BGR2YCrCb);
imshow("hsv", hsv);
imshow("yuv", yuv);
imshow("ycrcb", ycrcb);

/*
* 提取图像前景和背景
*/
Mat src2 = imread("../images/boy.jpg");
imshow("input boy", src2);
cvtColor(src2, hsv, COLOR_BGR2HSV);
// 从HSV表中查到绿色的最低值和最高值,建立掩模
Mat mask, mask_not;
inRange(hsv, Scalar(35, 43, 46), Scalar(77, 255, 255), mask);
imshow("mask", mask);
Mat fg, bg;
// 提取背景
bitwise_and(src2, src2, bg, mask);
// 提取前景
bitwise_not(mask, mask_not);
imshow("mask_not", mask_not);
bitwise_and(src2, src2, fg, mask_not);
imshow("background", bg);
imshow("foreground" ,fg);

waitKey(0);
return 0;
}
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
import cv2 as cv

src = cv.imread("../images/test.png")
cv.namedWindow("rgb", cv.WINDOW_AUTOSIZE)
cv.imshow("rgb", src)

# RGB to HSV
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV)
cv.imshow("hsv", hsv)

# RGB to YUV
yuv = cv.cvtColor(src, cv.COLOR_BGR2YUV)
cv.imshow("yuv", yuv)

# RGB to YUV
ycrcb = cv.cvtColor(src, cv.COLOR_BGR2YCrCb)
cv.imshow("ycrcb", ycrcb)

src2 = cv.imread("../images/boy.jpg");
cv.imshow("src2", src2)
hsv = cv.cvtColor(src2, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv, (35, 43, 46), (99, 255, 255))
dst = cv.bitwise_and(src2, src2, mask=mask)
cv.imshow("mask", mask)
cv.imshow("dst", dst)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github