fanfuhan OpenCV 教學011 ~ opencv-011-圖像像素歸一化


資料來源: https://fanfuhan.github.io/

https://fanfuhan.github.io/2019/03/25/opencv-011/


GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV



C++

#include 
#include 

using namespace std;
using namespace cv;

/*
 * 图像像素归一化
 */
int main() {
    Mat src = imread("../images/test.png");
    if (src.empty()) {
        cout << "could not load image.." << endl;
    }
    // imshow("input", src);

    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    imshow("input", gray);

    // 显示图像用uchar类型,计算时转为float类型
    gray.convertTo(gray, CV_32F);

    // NORM_MINMAX
    Mat dst = Mat::zeros(gray.size(), CV_32FC1);
    normalize(gray, dst, 1.0, 0, NORM_MINMAX);
    Mat res = dst * 255;
    res.convertTo(dst, CV_8UC1); // 显示图像用uchar类型
    imshow("NORM_MINMAX", dst);

    // scale and shift by NORM_INF
    normalize(gray, dst, 1.0, 0, NORM_INF);
    res = dst * 255;
    res.convertTo(dst, CV_8UC1);
    imshow("NORM_INF", dst);

    // scale and shift by NORM_L1
    normalize(gray, dst, 1.0, 0, NORM_L1);
    res = dst * 10000000;
    res.convertTo(dst, CV_8UC1);
    imshow("NORM_L1", dst);

    // scale and shift by NORM_L2
    normalize(gray, dst, 1.0, 0, NORM_L2);
    res = dst * 10000;
    res.convertTo(dst, CV_8UC1);
    imshow("NORM_L2", dst);

    waitKey(0);
    return 0;
}


Python

import cv2 as cv
import numpy as np

src = cv.imread("D:/vcprojects/images/test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)

# 转换为浮点数类型数组
gray = np.float32(gray)
print(gray)

# scale and shift by NORM_MINMAX
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=0, beta=1.0, norm_type=cv.NORM_MINMAX)
print(dst)
cv.imshow("NORM_MINMAX", np.uint8(dst*255))

# scale and shift by NORM_INF
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_INF)
print(dst)
cv.imshow("NORM_INF", np.uint8(dst*255))

# scale and shift by NORM_L1
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_L1)
print(dst)
cv.imshow("NORM_L1", np.uint8(dst*10000000))

# scale and shift by NORM_L2
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_L2)
print(dst)
cv.imshow("NORM_L2", np.uint8(dst*10000))

cv.waitKey(0)
cv.destroyAllWindows()

相关文章