简答题
偏难
#19552
图像压缩 【问题描述】 1. 灰度图像有 256 级灰阶,编码 00-FF,对应 0-255,即图像有很多点,每个点取值是 00 到 FF。编程压缩到 16 级…
图像压缩
【问题描述】
1. 灰度图像有 256 级灰阶,编码 00-FF,对应 0-255,即图像有很多点,每个点取值是 00 到 FF。编程压缩到 16 级灰阶,对应 0-F。
2. 压缩规则:统计出每种灰阶的数量,取数量最多的前 16 种灰阶(如某种灰阶的数量与另外一种灰阶的数量相同,则以灰阶值从小到大为序),分别编号 0-F。其他灰阶转换到最近的 16 种灰阶之一,将某个点灰阶数与 16 种灰阶种的一种相减,绝对值最小即为最近。
3. 输入:多行数据,每行数据等长,每两个字符构成一个点,十六进制;输出:首先连续最多输出 16 种灰阶编码,不足 16 种灰阶就按实际输出;然后各行输出压缩后的编码,每行等长。
【输入描述】
1. 第 1 次输入正整数 n,表示有多少行数据。
2. 随后输入 n 行数据。
3. 特别提示:常规程序中,输入时好习惯是有提示。考试时由于系统限定,输入时所有 input()函数不可有提示信息。
【输出描述】
1. 首先输出 16 种灰阶编码,共计 32 个字符。不足 16 种按实际输出。输出数量最多的 16 种灰阶,从多到少;如某种灰阶的数量与另外一种灰阶的数量相同,则以灰阶值从小到大为序;
2. 特别提示:注意输出字母为大写,小写将判为错误,数本身与字母 T 和 F 之前没有空格。
【样例输入 1】
【样例输出 1】
答案与解析
正确答案:<pre class="brush:python;toolbar:false">#图像压缩
def composePixel(topDict,srcVal):
if srcVal in topDict:
return hex(topDict[srcVal])[2:].upper()
else:#不在列表中,计算最近距离
nearest = 255
nearestKey = "FF"
for k,v in topDict.items():
tmpDistance = abs(int(srcVal,16)-int(k,16))
if tmpDistance < nearest:
nearest = tmpDistance
nearestKey = v
return hex(nearestKey)[2:].upper()
N = int(input())
dictDot = {}
rawData = []
newData = []
for i in range(N):
dataLine = input()
rawData.append(dataLine)
charCount = len(dataLine)
groupCount = charCount //2
for i in range(groupCount):
twoHex = dataLine[i*2:i*2+2] #两个十六进制字符
dictDot[twoHex] = dictDot.get(twoHex,0) + 1
top16 = sorted(dictDot.items(), key = lambda x: (x[1],-int(x[0],16)), reverse = True)[:16]
top16Dict = {k:x for x,(k,v) in enumerate(top16)}
for dataLine in rawData:
groupCount = len(dataLine) // 2
tmp = ""
for i in range(groupCount):
tmp += composePixel(top16Dict,dataLine[i*2:i*2+2])
newData.append(tmp)
for top in top16:
print(top[0],end="")
print()
for everyLine in newData:
print(everyLine)</pre><p><br/></p>
这道题暂未补解析。