我们将图像的值由256^3压缩至4^3,即将\text{RGB}的值只取{32, 96, 160, 224},这被称作色彩量化。色彩的值按照下面的方式定义:
val = { 32 ( 0 <= val < 64)
96 ( 64 <= val < 128)
160 (128 <= val < 192)
224 (192 <= val < 256)
python 实现:
import cv2
import numpy as np
# Read image
img = cv2.imread("imori.jpg")
# Dicrease color
out = img.copy()
out = out // 64 * 64 + 32
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
C++实现:
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <math.h>
int main(int argc, const char* argv[]){
cv::Mat img = cv::imread("imori.jpg", cv::IMREAD_COLOR);
int width = img.rows;
int height = img.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
for (int j = 0; j < height; j++){
for (int i = 0; i < width; i++){
for (int c = 0; c < 3; c++){
out.at<cv::Vec3b>(j,i)[c] = (uchar)(floor((double)img.at<cv::Vec3b>(j,i)[c] / 64) * 64 + 32);
}
}
}
//cv::imwrite("out.jpg", out);
cv::imshow("answer", out);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
输入:
输出: