样例输入:
16 11 10 16 24 40 51 61
12 12 14 19 26 58 60 55
14 13 16 24 40 57 69 56
14 17 22 29 51 87 80 62
18 22 37 56 68 109 103 77
24 35 55 64 81 104 113 92
49 64 78 87 103 121 120 101
72 92 95 98 112 100 103 99
26
2
-26 -3 0 -3 -2 -6 2 -4 1 -3 1 1 5 1 2 -1 1 -1 2 0 0 0 0 0 -1 -1
样例输出:
62 65 57 60 72 63 60 82
57 55 56 82 108 87 62 71
58 50 60 111 148 114 67 65
65 55 66 120 155 114 68 70
70 63 67 101 122 88 60 78
71 71 64 70 80 62 56 81
75 82 67 54 63 65 66 83
81 94 75 54 68 81 81 87
备注:代码过程中要注意边界问题,本题是图像的边界问题,即关键代码:
得40分的就是没有考虑边界问题,下边是python完整代码:
import math
from math import pi
#执行输入
u = [[] for i in range(8)]
for k in range(8):
u[k] = [int(i) for i in input().split(' ')]
n = int(input())
T = int(input())
data = [int(i) for i in input().split(' ')]
#执行
#1.读入量化矩阵(输入时 u 即为量化矩阵)
#2.初始化8*8矩阵
M = [[0 for i in range(8)] for j in range(8)]
result = [[0 for i in range(8)] for j in range(8)]
#3.读入扫描数据,对M进行填充
#先对data进行填充0
num_0 = 64 - len(data)
if(num_0>=1):
for i in range(num_0):
data.append(0)
#读入索引矩阵
index = [[0,1,5,6,14,15,27,28],[2,4,7,13,16,26,29,42],[3,8,12,17,25,30,41,43],[9,11,18,24,31,40,44,53],[10,19,23,32,39,45,52,54],[20,22,33,38,46,51,55,60],[21,34,37,47,50,56,59,61],[35,36,48,49,57,58,62,63]]
#按照索引矩阵落值
for i in range(8):
for j in range(8):
M[i][j] = data[index[i][j]]
if(T==0):
for i in range(8):
for j in range(8):
if (j == 7):
print(M[i][j])
break
print(M[i][j], end=' ')
#与量化矩阵逐项相乘
for i in range(8):
for j in range(8):
M[i][j] = M[i][j]*u[i][j]
result[i][j] = M[i][j]
#离散余弦反变换
for i in range(8):
for j in range(8):
sum_ = 0.0
for x in range(8):
if (x == 0):
x1 = math.sqrt(0.5)
else:
x1 = 1
x3 = math.cos(pi*(i+0.5)*x/8)
for y in range(8):
if (y == 0):
x2 = math.sqrt(0.5)
else:
x2 = 1
x4 = math.cos(pi*(j+0.5)*y/8)
sum_ += x1*x2*M[x][y]*x3*x4
result[i][j] = round(sum_*1.0/4 + 128)
if(result[i][j]>255):
result[i][j] = 255
elif(result[i][j]<0):
result[i][j] = 0
else:
pass
if(T==1):
for i in range(8):
for j in range(8):
if (j == 7):
print(M[i][j])
break
print(M[i][j], end=' ')
if(T==2):
for i in range(8):
for j in range(8):
if (j == 7):
print(result[i][j])
break
print(result[i][j], end=' ')