針對彩色圖像實現了arnold置換與置換還原,解決了cv2.imread()讀取圖像偏色、處理后無結果顯示或顯示結果為純色圖像等問題。
參考來源:
https://blog.csdn.net/weixin_43924621/article/details/116211424
import cv2 import numpy as np import matplotlib.image as mpimg def arnold(img, shuffle_times, a, b): r, c, d = img.shape # 高,寬,通道個數 p = np.zeros(img.shape, np.uint8) for times in range(shuffle_times): # 置亂次數 for i in range(r): for j in range(c): x = (i + b * j) % r y = (a * i + (a * b + 1) * j) % c p[x, y, :] = img[i, j, :] img = np.copy(p) # 深復制 return p img = mpimg.imread('lena.bmp') img = img[:, :, [2, 1, 0]] # 解決顯色問題 new = arnold(img, 1, 1, 3) cv2.imshow('picture', new) cv2.waitKey(0) cv2.imwrite('new.bmp', new)
置換后還原代碼:
def de_arnold(img,shuffle_time,a,b): r, c, d = img.shape dp = np.zeros(img.shape, np.uint8) for s in range(shuffle_time): for i in range(r): for j in range(c): x = ((a * b + 1) * i - b * j) % r y = (-a * i + j) % c dp[x, y, :] = img[i, j, :] img = np.copy(dp) return img img = mpimg.imread('new.bmp') img = img[:, :, [2, 1, 0]] new = de_arnold(img, 1, 1, 3) cv2.imshow('picture', new) cv2.waitKey(0)
1. arnold() 和 de_arnold()中 shuffle_time,a,b 三個參數的數值需要對應才能實現圖像還原。
2. de_arnold()中的img為運行arnold()后通過cv2.imwrite()保存的結果。
3. 示例圖為512*512的lena.bmp,此博客不支持上傳.bmp格式的圖片。
置亂后的圖像(shuffle_time=1,a=1,b=3):
還原:
后續可在此基礎上使用離散小波變換繼續對圖像進行處理。