Python

[OpenCV-Python Tutorials]-Image

2021-08-06  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读