有关openCv的一些操作

这段代码展示了如何使用OpenCV库进行图像处理,包括读取图像、显示图像、转换为灰度图、调整大小、从摄像头捕获视频、颜色过滤、背景颜色替换以及将图像像素值写入文本文件等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>
#include<stdio.h>
#include<fstream>
using namespace cv;
using namespace std;
string DoubleToString(double Input)
{
    stringstream Oss;
    Oss << Input;
    return Oss.str();
}
string path = "C:\\Users\\Sunym\\Desktop\\hongzh.jpg";
string outToPath = "C:\\Users\\Sunym\\Desktop\\原图.txt";
void showGreyOriSmallPic() {
    cout << "Built with OpenCV " << CV_VERSION << endl;
    Mat image = imread("C:\\Users\\Sunym\\Desktop\\hongzh.jpg");//见注1 
    imshow("原始图像", image);//见注2
    resize(image, image, Size(360, 202));//见注3
    imwrite("D:\\xinyuan.jpg", image);//见注4
    imshow("缩小图像", image);
    cvtColor(image, image, CV_RGB2GRAY);//见注5
    imshow("灰度图像", image);
    waitKey(0);//见注6
}
void getCamera() {
    VideoCapture cap(0); //capture the video from web cam

    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the web cam" << endl;
        return ;
    }

    namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"

    int iLowH = 100;
    int iHighH = 140;

    int iLowS = 90;
    int iHighS = 255;

    int iLowV = 90;
    int iHighV = 255;

    //Create trackbars in "Control" window
    cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
    cvCreateTrackbar("HighH", "Control", &iHighH, 179);

    cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
    cvCreateTrackbar("HighS", "Control", &iHighS, 255);

    cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
    cvCreateTrackbar("HighV", "Control", &iHighV, 255);

    while (true)
    {
        Mat imgOriginal;

        bool bSuccess = cap.read(imgOriginal); // read a new frame from video

        if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read a frame from video stream" << endl;
            break;
        }

        Mat imgHSV;
        vector<Mat> hsvSplit;
        cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

        //因为我们读取的是彩色图,直方图均衡化需要在HSV空间做
        split(imgHSV, hsvSplit);
        equalizeHist(hsvSplit[2], hsvSplit[2]);
        merge(hsvSplit, imgHSV);
        Mat imgThresholded;

        inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image

        //开操作 (去除一些噪点)
        Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
        morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);

        //闭操作 (连接一些连通域)
        morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element);

        imshow("Thresholded Image", imgThresholded); //show the thresholded image
        imshow("Original", imgOriginal); //show the original image

        char key = (char)waitKey(300);
        if (key == 27)
            break;
    }

}
void updateBackGroundColor() {
    Mat src;
    src = imread(path);    //图像加载
    if (src.empty()) {
        cout << "could not load image..." << endl;
        return ;
    }
    else cout << "load succsessful." << endl;
    imshow("input", src);


    Mat dst;
    dst.create(src.size(), src.type());  //创建类型一样的图片
    int height = src.rows;              //获取图像的行
    int width = src.cols;              //获取图像的列
    int nc = src.channels();  //通道

    for (int row = 0; row < height; row++)
        for (int col = 0; col < width; col++) {
            if (nc == 1) {
                int gray = src.at<uchar>(row, col);
                src.at<uchar>(row, col) = 255 - gray;
            }
            else if (nc == 3) {
                int    b = src.at<Vec3b>(row, col)[0];  //读取通道值
                int    g = src.at<Vec3b>(row, col)[1];
                int    r = src.at<Vec3b>(row, col)[2];
                dst.at<Vec3b>(row, col)[0] = 0;      //给新图像赋值
                dst.at<Vec3b>(row, col)[1] = 0;      //这个通道清零
                dst.at<Vec3b>(row, col)[2] = r;

            }
        }
    //bitwise_not(src, dst);
    imshow("output", dst);
    waitKey(0);
}
void getCamera2() {
    VideoCapture cap(0); //capture the video from web cam

    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the web cam" << endl;
        return ;
    }

    namedWindow("control", 1);
    int ctrl = 0;
    createTrackbar("ctrl", "control", &ctrl, 7);

    while (true)
    {
        Mat imgOriginal;

        bool bSuccess = cap.read(imgOriginal); // read a new frame from video
        if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read a frame from video stream" << endl;
            break;
        }

        // imgOriginal = imread("4.jpg");

        Mat imgHSV, imgBGR;
        Mat imgThresholded;

        if (0)
        {
            vector<Mat> hsvSplit;   //创建向量容器,存放HSV的三通道数据
            cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
            split(imgHSV, hsvSplit);            //分类原图像的HSV三通道
            equalizeHist(hsvSplit[2], hsvSplit[2]);    //对HSV的亮度通道进行直方图均衡
            merge(hsvSplit, imgHSV);                   //合并三种通道
            cvtColor(imgHSV, imgBGR, COLOR_HSV2BGR);    //将HSV空间转回至RGB空间,为接下来的颜色识别做准备
        }
        else
        {
            imgBGR = imgOriginal.clone();
        }

        switch (ctrl)
        {
        case 0:
        {
            inRange(imgBGR, Scalar(128, 0, 0), Scalar(255, 127, 127), imgThresholded); //蓝色
            break;
        }
        case 1:
        {
            inRange(imgBGR, Scalar(128, 128, 128), Scalar(255, 255, 255), imgThresholded); //白色
            break;
        }
        case 2:
        {
            inRange(imgBGR, Scalar(128, 128, 0), Scalar(255, 255, 127), imgThresholded); //靛色
            break;
        }
        case 3:
        {
            inRange(imgBGR, Scalar(128, 0, 128), Scalar(255, 127, 255), imgThresholded); //紫色
            break;
        }
        case 4:
        {
            inRange(imgBGR, Scalar(0, 128, 128), Scalar(127, 255, 255), imgThresholded); //黄色
            break;
        }
        case 5:
        {
            inRange(imgBGR, Scalar(0, 128, 0), Scalar(127, 255, 127), imgThresholded); //绿色
            break;
        }
        case 6:
        {
            inRange(imgBGR, Scalar(0, 0, 128), Scalar(127, 127, 255), imgThresholded); //红色
            break;
        }
        case 7:
        {
            inRange(imgBGR, Scalar(0, 0, 0), Scalar(127, 127, 127), imgThresholded); //黑色
            break;
        }
        }

        imshow("形态学去噪声前", imgThresholded);

        Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
        morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);
        morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element);

        imshow("Thresholded Image", imgThresholded); //show the thresholded image
        imshow("直方图均衡以后", imgBGR);
        imshow("Original", imgOriginal); //show the original image

        char key = (char)waitKey(300);
        if (key == 27)
            break;
    }

}
void getRGB() {
    IplImage* img = cvLoadImage(path.c_str(), 1);
    CvScalar s;
    for (int i = 0; i < img->height; i++)

    {
        for (int j = 0; j < img->width; j++)

        {
            s = cvGet2D(img, i, j);     // get the (i,j) pixel value
            printf("B=%f, G=%f, R=%f ", s.val[0], s.val[1], s.val[2]);
            s.val[0] = 111;
            s.val[1] = 111;
            s.val[2] = 111;
            cvSet2D(img, i, j, s);       //set the (i,j) pixel value
        }
    }
}
void toText() {
    ofstream ofs;

    IplImage* img = cvLoadImage(path.c_str(), 1);
    CvScalar s;
    for (int i = 0; i < img->height; i++)

    {
        for (int j = 0; j < img->width; j++)

        {
            s = cvGet2D(img, i, j);     // get the (i,j) pixel value
            printf("B=%f, G=%f, R=%f ", s.val[0], s.val[1], s.val[2]);
            ofs.open(outToPath, ios::out | ios::app);
            if (ofs.is_open()) {
                ofs << DoubleToString(s.val[0]);
                ofs << DoubleToString(s.val[1]);
                ofs << DoubleToString(s.val[2]);
                ofs << ' ';
            }
            s.val[0] = 111;
            s.val[1] = 111;
            s.val[2] = 111;
            cvSet2D(img, i, j, s);       //set the (i,j) pixel value
            
        }
        ofs << '\n';
        ofs.close();
    }
    ofs.close();
}
int main()
{
    //showGreyOriSmallPic();//显示原始图像,缩小图像,灰度图像
    //getCamera();//调用摄像机
    //updateBackGroundColor();//修改背景颜色
    //getCamera2();//识别8种颜色
    //getRGB();//识别整张图片RGB
    //记得include<fstream>
    //toText();//将识别出的txt导入文件中
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值