OpenCV:四、图像的基础操作

2020-08-22  本文已影响0人  马洪滔

前言

在上一章中描述了如何使用自己实现掩膜运算以及调用cv :: filter2D函数对图像进行掩膜运算矩阵的掩膜运算

目标

本章中,将学习如何:

读写像素

Scalar gray = img.at<uchar>(i,j) 或者 Scalar intensity = img.at<uchar>(Point(j,i))
Vec3f rgb = img.at<Vec3f>(i,j) 或者 Vec3f rgb = img.at<Vec3f>(Point(j,i)) 
float blue = bgr.val[0];
float green = bgr.val[1];
float red = bgr.val[2];

修改像素值

img.at<uchar>(Point(j,i)) = 128;
img.at<Vec3f>(Point(j,i)) [0] = 128; //blue
img.at<Vec3f>(Point(j,i)) [1] = 128; //green
img.at<Vec3f>(Point(j,i)) [2] = 128; //red
img = Scalar(0)
Rect r(10,10,100,100);
Mat roiImg = img(r);

源代码

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
        Mat grayImage;
    src = imread("../data/HappyFish.jpg", IMREAD_UNCHANGED);
    if (src.empty())
    {
        printf("Could not find the image!\n");
        return -1;
    }
    namedWindow("input", WINDOW_NORMAL);
    imshow("input", src);
    cvtColor(src, grayImage, COLOR_BGR2GRAY);
    namedWindow("gray", WINDOW_NORMAL);
    imshow("gray", grayImage);
    int rows = grayImage.rows;
    int cols = grayImage.cols;
    dst = Mat(grayImage.size(), grayImage.type());  // 示例对象
    // 反差图像
       dst.create(src.size(), src.type());
    int rows = src.rows;
    int cols = src.cols;
    int chls = src.channels();
    for (int row = 0; row < rows; row++)
    {
        for (int col = 0; col < cols; col++)
        {
            if (chls == 1)
            {
                int gray = grayImage.at<uchar>(row, col);
                dst.at<uchar>(row, col) = 255 - gray;
            }
            else if (chls == 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] = 255 - b;
                dst.at<Vec3b>(row, col)[1] = 255 - g;
                dst.at<Vec3b>(row, col)[2] = 255 - r;
            }

        }
    }
       // 按位取反,和上述功能一致
    bitwise_not(src, dst);
    namedWindow("output", WINDOW_NORMAL);
    imshow("output", dst);
    waitKey(0); // Wait for a keystroke in the window
        return 0;
    }

说明

上一篇 下一篇

猜你喜欢

热点阅读