classNineGrid: def__init__(self, a, d, flag): self.a = a self.d = d self.flag = flag
defbest_pixel(nine, k): min_d = 255 min_x = 0 min_y = 0 for i inrange(3): for j inrange(3): if nine.flag[i][j] == k and nine.d[i][j] < min_d: min_x = i min_y = j min_d = nine.d[i][j] return nine.a[min_x][min_y]
def_1d_2_2d(x): if x == 0: return0, 0 elif x == 1: return0, 1 elif x == 2: return0, 2 elif x == 3: return1, 2 elif x == 4: return2, 2 elif x == 5: return2, 1 elif x == 6: return2, 0 elif x == 7: return1, 0
deffind_best(channel, x, y): a = [[0]*3for i inrange(3)] for i inrange(3): for j inrange(3): a[i][j] = channel[x - 1 + i][y - 1 + j] d = [[0]*3for i inrange(3)] for i inrange(3): for j inrange(3): d[i][j] = abs(int(a[i][j]) - int(a[1][1])) dp = [0] * 8 for i inrange(8): dx, dy = _1d_2_2d(i) dp[i] = d[dx][dy] dps = sorted(dp) max_index = dps.index(max(dps)) flag = [[0]*3for i inrange(3)] for i inrange(3): for j inrange(3): if d[i][j] >= dps[max_index]: flag[i][j] = 1 # 中心点暂时不分区 flag[1][1] = 2
# 枚举匹配flag特征 # A:B = 1:7 cnt = 0 for i inrange(3): for j inrange(3): if flag[i][j] == 0: cnt += 1 min_d = 255 min_x = 0 min_y = 0 if cnt == 0: for i inrange(3): for j inrange(3): if d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 1: for i inrange(3): for j inrange(3): if flag[i][j] == 1and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 7: for i inrange(3): for j inrange(3): if flag[i][j] == 0and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 2: for i inrange(3): for j inrange(3): if flag[i][j] == 1and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 6: for i inrange(3): for j inrange(3): if flag[i][j] == 0and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 3: for i inrange(3): for j inrange(3): if flag[i][j] == 1and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 5: for i inrange(3): for j inrange(3): if flag[i][j] == 0and d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j elif cnt == 4: for i inrange(3): for j inrange(3): if d[i][j] < min_d: min_d = d[i][j] min_x = i min_y = j return a[min_x][min_y]
defdenoise(channel): row, col = channel.shape for i inrange(1, row - 1): for j inrange(1, col - 1): channel[i][j] = find_best(channel, i, j) return channel
defmain(addr): img = cv.imread(addr, 1) b, g, r = cv.split(img) b = denoise(b) g = denoise(g) r = denoise(r) img = cv.merge((b, g, r)) cv.imwrite('denoise_' + addr, img)
if __name__ == '__main__': img_addr = 'noise_img.png' main(img_addr)