Simple manipulation of object image pixels

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


using namespace std;
using namespace cv;


int main() {
    Mat src, gray_src;
    src = imread("/Users/apple/Desktop/test3.png", IMREAD_COLOR);
    if (src.empty()) { // if (!src.data())
        cout << "could not load image..." << endl;
        return -1;
    }

    namedWindow("test opencv setup", CV_WINDOW_AUTOSIZE);
    imshow("test opencv setup", src);
    
    cvtColor(src, gray_src, CV_BGR2GRAY);
    namedWindow("output", CV_WINDOW_AUTOSIZE);
    imshow("output", gray_src);
    
    int height = gray_src.rows;
    int width = gray_src.cols;
    // single channel
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            int gray = gray_src.at<uchar>(i, j);
            gray_src.at<uchar>(i, j) = 255 - gray;
        }
    }
    imshow("invert gray", gray_src);
    
    
    Mat dst;
    dst.create(src.size(), src.type());
    height = src.rows;
    width = src.cols;
    int nc = src.channels();
    
    imshow("dst", dst);
    
    Mat new_gray;
    new_gray.create(src.size(), CV_8UC1);
    
    
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (nc == 1) {
                int gray = gray_src.at<uchar>(i, j);
                gray_src.at<uchar>(i, j) = 255 - gray;
            }
            else if (nc == 3) {
                // Use Vec3b to read three-channel pixels
                // Vec3b corresponds to uchar type data whose order is blue green red
                // Vec3f corresponds to three-channel float type
    
                dst.at<Vec3b>(i, j)[0] = 255 - src.at<Vec3b>(i, j)[0];
                dst.at<Vec3b>(i, j)[1] = 255 - src.at<Vec3b>(i, j)[1];
                dst.at<Vec3b>(i, j)[2] = 255 - src.at<Vec3b>(i, j)[2];
                
                new_gray.at<uchar>(i, j) = min(src.at<Vec3b>(i, j)[0], min(src.at<Vec3b>(i, j)[1], src.at<Vec3b>(i, j)[2]));
            }
        }
    }
    
    //bitwise_not(dst, dst); // Bitwise operation as above
    imshow("3 channels invert", dst);
    
    
    // Convert CV_8UC1 to CV_32F1
    src.convertTo(dst, CV_32FC1);
    
    
    imshow("new gray", new_gray);
    
    waitKey(0);
    
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325734473&siteId=291194637