python PIL Image 图片与矩阵的转换, 加密

对图片进行简单的加密

  1. 直接在字节上进行异或操作,这样破坏了图片格式。2. 百度了一下,发现可以直接变动像素的位置实现某种程度上的加密。

流程上:

  1. 获取图片的像素数据
  2. 随机化一个序列,根据这个序列重新排列像素,需要把像素值存储到矩阵中
  3. 随机后的矩阵转为图片
  • 如何获取图片的像素
1. p = img.load()  # img = Image.open('x.png')
# 可以用p[x,y]的方式取像素
2. arr = np.array(img) # np = numpy
  • 随机序列
random.seed(1)
random.shuffle()
def convert(content):
    i = BytesIO(content)
    img = Image.open(i)
    width, height = img.size
    x, y = range(height), range(width)
    random.seed(width+height)
    random.shuffle(x)
    random.shuffle(y)
    temp = np.zeros((height, width, 3), dtype='|u1') # dtype 不指定的化 在Image.fromarray 时会有异常
    g = np.array(img)
    for i in range(height):
        for j in range(width):
            temp[i][j] = g[x[i]][y[j]]
    new_img = Image.fromarray(temp)
    new_img.show()

测试:
python PIL Image 图片与矩阵的转换, 加密
python PIL Image 图片与矩阵的转换, 加密

python PIL Image 图片与矩阵的转换, 加密

结果发现,解开后的图片和原来的图片内容是差不多的,但质量上下降很多,再次百度
发现, img.save时 有quality参数可选
修改qulity参数后,看上去没有那么大的区别了
python PIL Image 图片与矩阵的转换, 加密

但是通过查看矩阵的时候,发现还是有很多差距的
python PIL Image 图片与矩阵的转换, 加密

quality设置为100都不能彻底解决问题,想到这是不是Image模块本身的问题,于是换用cv2

def _convert(content, de_encry=False):
    # i = StringIO(content)
    # img = cv2.imread(i)
    img = np.fromstring(content, np.uint8)
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    print img.shape
    height, width, c = img.shape
    x, y = range(height), range(width)
    random.seed(width+height)
    random.shuffle(x)
    random.shuffle(y)
    temp = np.zeros((height, width, 3), dtype='uint8')
    g = img
    if de_encry is False:
        ff(temp, g, range(height), range(width), x, y)
    else:
        ff(temp, g, x, y, range(height), range(width))
    cv2.imwrite('n.jpg', temp, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
    cv2.imshow('img', temp)

结果出来后,在矩阵上看仍有很大不同, 再次去搜索,发现保存为bmp,可以解决失真的问题233
python PIL Image 图片与矩阵的转换, 加密