美文网首页Python
[OpenCV-Python Tutorials]-Image

[OpenCV-Python Tutorials]-Image

作者: 六千宛 | 来源:发表于2021-08-06 12:04 被阅读0次

    Learn to change images between different color spaces. Plus learn to track a colored object in a video.

    Changing Color-space

    cv.COLOR_BGR2GRAY和 cv.COLOR_BGR2HSV
    
    #include <opencv2\opencv.hpp>
     
    using namespace std;
    using namespace cv;
     
    int main()
    {
        cv::Mat src = cv::imread("C:\\Users\\dell\\Desktop\\xin1.jpg", 1);
        if (src.empty() || src.channels() != 3)
        {
            cout << "Source image load error!" << endl;
            return -1;
        }
     
        //采用CV_BGR2GRAY,转换公式Gray = 0.1140*B + 0.5870*G + 0.2989*R
        cv::Mat bgr2grayImg;    
        cvtColor(src, bgr2grayImg, CV_BGR2GRAY);    
     
        //采用CV_RGB2GRAY,转换公式Gray = 0.1140*R + 0.5870*G + 0.2989*B
        cv::Mat rgb2grayImg;
        cvtColor(src, rgb2grayImg, CV_RGB2GRAY);    
     
        //采用CV_GRAY2BGR,转换公式B = G = R = Gray
        cv::Mat gray2bgrImg;
        cvtColor(bgr2grayImg, gray2bgrImg, CV_GRAY2BGR);    
     
        //采用CV_GRAY2RGB,转换公式R = G = B = Gray
        cv::Mat gray2rgbImg;
        cvtColor(rgb2grayImg, gray2rgbImg, CV_GRAY2RGB);    
        
        waitKey(0);
        return 0;
    

    色彩空间转换

    import os
    import cv2
    save="c:/"
    
    img=cv2.imread("c:/ddd.jpg")#读取文件
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#色彩空间的转化
    cv2.imwrite(os.path.join(save,"eee.jpg"),hsv)#写入图片文件
    

    Object Tracking

    import cv2 as cv
    import numpy as np
    cap = cv.VideoCapture(0)
    while(1):
    # Take each frame
       _, frame = cap.read()
    # Convert BGR to HSV
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    # define range of blue color in HSV
        lower_blue = np.array([110,50,50])
        upper_blue = np.array([130,255,255])
    # Threshold the HSV image to get only blue colors
        mask = cv.inRange(hsv, lower_blue, upper_blue)
    # Bitwise-AND mask and original image
        res = cv.bitwise_and(frame,frame, mask= mask)
        cv.imshow('frame',frame)
        cv.imshow('mask',mask)
        cv.imshow('res',res)
        k = cv.waitKey(5) & 0xFF
        if k == 27:
           break
    cv.destroyAllWindows()
    
    image.png

    相关文章

      网友评论

        本文标题:[OpenCV-Python Tutorials]-Image

        本文链接:https://www.haomeiwen.com/subject/oxmbvltx.html