You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
python/GESP/灰阶图像/灰阶图像 - 第一个版本.cpp

92 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 256;
//桶
int bucket[N];//0 ~ 255
//原始的字符串数组
string q[30];
//将一个16进制的灰阶转为一个整数方便用来当数组的下标索引值
int get(char a, char b) {
return (a - '0') * 16 + (b - '0');
}
//将一个十进制的灰阶值[0,255]转化成十六进制[0,FF]
string toHex(int x) {
string res;
int a = x % 16; // 0 ~ 15
int b = x / 16; //
if (a >= 10)
res = 'A' + a - 10;
else
res = '0' + a;
if (b >= 10)
res = res + 'A' + b - 10;
else
res = res + '0' + b;
}
//结构体,用来把桶中的灰阶按数量排序用的
struct Node {
int id;//数组下标
int cnt;//个数
const bool operator<(const Node &b) const {
if (cnt == b.cnt)
return id < b.id;
return cnt > b.cnt;
}
};
vector<Node> vec;//需要把bucket组装成Node放到数组p中才能使用结构体排序吧
int main() {
int n;
cin >> n;//有n行数据组成了图像
for (int i = 1; i <= n; i++) {
string s;
q[i] = s;//存入原始字符串数组
cin >> s;
for (int j = 0; j < s.size(); j += 2) {
char a = s[j], b = s[j + 1];
//比如a='A' b='B' AB
//我需要把 AB计数看看有多少个
//如果我们用数组+桶来计数的话,那个桶的内容值就是数量,下标索引应该是什么东西
//比如100就是一种淡灰色现在这个淡灰色是 AB FF
int k = get(a, b); //灰阶对应的数组位置
bucket[k]++;
}
}
//找出前16位使用频率高的灰阶
//排序,按什么排序呢?
//1、按数量数量多的在前
//2、如果数量一样多呢?桶中索引小的在前
for (int i = 0; i <= 255; i++) {
vec.push_back({i, bucket[i]});
}
sort(vec.begin(), vec.end());
//有了一个已经排好序的vector<Node>
//vec[0]~vec[15]; vec[0].id vec[0].cnt
//toHex(vec[0].id)
// AA BB CC DD
for (int i = 1; i <= n; i++) { //枚举每个原始字符串每2个一组判断这个小串应该与尺子数组中的哪一个更接近
for (int j = 0; j < q[0].size(); j += 2) {
char a = q[j], b = q[j + 1]; //0 F ,0 F
//计算ab组装出的短串与上面vec中的前16个哪个距离最短
int x = get(a, b);
int mi = INT_MAX;
int mi_p = 0;
for (int k = 0; k < min(16, vec.size()); k++) { //16是有风险的因为可能没有16个那么多
if (mi > abs(vec[k] - x)) {
mi = abs(vec[k] - x);
mi_p = k;
}
}
//mi_p [0,255] -> 十六进制
//将当前的a,b这个值修改为mi_p这个灰阶值
cout << toHex(mi_p);
}
}
return 0;
}