009 图像色彩空间转换

2019-07-29  本文已影响0人  几时见得清梦
  1. 四种常见的色彩空间:RGB,HSV,YUV,YCrCb
    • cvtColor:OpenCV API,在不同色彩空间进行转换。
    • inRange:提取指定的色彩范围的区域的API,可以搭配HSV色彩空间使用。
HSV三个通道的取值范围
色彩空间转换结果
对hsv空间使用inRange取指定色彩范围

C++

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, const char *argv[])
{
    Mat src = imread("D:/vcprojects/images/cat.jpg");
    if (src.empty()) {
        printf("could not load image...\n");
        return -1;
    }
    namedWindow("input", WINDOW_AUTOSIZE);
    imshow("input", src);

    // RGB to HSV
    Mat hsv;
    cvtColor(src, hsv, COLOR_BGR2HSV);
    imshow("hsv", hsv);

    // RGB to YUV
    Mat yuv;
    cvtColor(src, yuv, COLOR_BGR2YUV);
    imshow("yuv", yuv);

    // RGB to YUV
    Mat ycrcb;
    cvtColor(src, ycrcb, COLOR_BGR2YCrCb);
    imshow("ycrcb", ycrcb);

    Mat src2 = imread("D:/javaopencv/tinygreen.png");
    imshow("src2", src2);
    cvtColor(src2, hsv, COLOR_BGR2HSV);
    Mat mask;
    inRange(hsv, Scalar(35, 43, 46), Scalar(99, 255, 255), mask);
    imshow("mask", mask);

    waitKey(0);
    return 0;
}

Python

import cv2 as cv

src = cv.imread("D:/vcprojects/images/cat.jpg")
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("D:/javaopencv/tinygreen.png");
cv.imshow("src2", src2)
hsv = cv.cvtColor(src2, cv.COLOR_BGR2HSV) #转到hsv
mask = cv.inRange(hsv, (35, 43, 46), (77, 255, 255))#三个参数:第一个是输入图像,通常为hsv空间的图像;第二个参数是三个通道对应的低值;第三个参数是三个通道对应的高值;返回像素提取结果。
cv.imshow("mask", mask)

cv.waitKey(0)
cv.destroyAllWindows()
上一篇下一篇

猜你喜欢

热点阅读