我再次需要原始图像,但它返回灰度 我的老师说开始做色图,并说它发生在matlab中。所以我也想在python中做类似的任务 这是我的代码看看 请帮忙
ENCRYPTION:
import numpy as np
from PIL import Image
x = Image.open('1.jpg', 'r')
x = x.convert('L')
y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value # dtype is int type reshape used to break 1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
w = Image.fromarray(y, mode='L')
w.save('grey_scale.bmp')
for i in range(len(z)):
for j in range(len(z[i])):
a = z[i][j]
p = int(bin(a)[2:])
p = '%08d' % p
p = p[::-1]
z[i][j] = int(p, 2)
#print(z)
C = Image.fromarray(z)
C.save('decryption.bmp')
print("DONE")
解密:
import numpy as np
from PIL import Image
x = Image.open('decryption.bmp', 'r')
y = np.asarray(x.getdata(), dtype=np.int).reshape((x.size[1], x.size[0]))#changed image to matrix getdata for matrix value
#print(y) # dtype is int type reshape used to break 1d array into 2d array
y = np.asarray(y, dtype=np.uint8)#if values still in range 0-255!
#print(y)
z = y
for i in range(len(z)):
for j in range(len(z[i])):
a = z[i][j]
p = int(bin(a)[2:])
p = '%08d' % p
p = p[::-1]
z[i][j] = int(p, 2)
#print(z)
C = Image.fromarray(z)
C.save('Final.bmp')
print("DONE")
答案 0 :(得分:0)
我认为(?)您正在寻找的是Colour Mapping函数,如:
def create_colourmap(colour, grey):
c_map = numpy.zeros((256,4), dtype=numpy.float64)
for i in range(colour.shape[0]):
for j in range(colour.shape[1]):
tone = grey[i,j]
c_map[tone,3] +=1
count = c_map[tone, 3]
c_map[tone,:3] = (c_map[tone,:3] * (count-1) + colour[i,j])/count
return c_map.astype(numpy.uint8)[:,:3]
这将为每个灰度值(或音调)提供一个颜色值。
您的“位反转”程序可以通过其他功能简化:
def reverse_bits(arr):
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
arr[i][j] = int('{0:08b}'.format(arr[i][j])[::-1], 2)
return arr
将所有这些放在一起,您的加密功能将是:
def encrypt(infile, outfile):
with Image.open(infile, 'r') as colour_img:
colour_arr = numpy.array(colour_img)
grey_img = colour_img.convert('L')
grey_arr = numpy.array(grey_img)
c_map = create_colourmap(colour_arr, grey_arr)
with Image.fromarray(c_map) as cmap_img:
cmap_img.save(outfile[:-4]+'_cmap.bmp')
grey_arr = reverse_bits(grey_arr)
with Image.fromarray(grey_arr) as c:
c.save(outfile)
print("Encryption DONE")
你的解密功能:
def decrypt(infile, outfile):
with Image.open(infile, 'r') as x:
y = numpy.array(x)
y = reverse_bits(y)
colour_arr = numpy.zeros((y.shape[0], y.shape[1], 3), dtype=numpy.uint8)
with Image.open(infile[:-4]+'_cmap.bmp') as cmap_img:
cmap = numpy.array(cmap_img)
for i in range(256):
colour_arr[y==i] = cmap[i]
with Image.fromarray(colour_arr) as c:
c.save(outfile)
print("Decryption DONE")
您会注意到颜色映射不会完全恢复图像颜色,但会给图像增加一些色调。我不知道你的作业是什么,但是你可能想要将彩色图像与加密图像一起发送,或者给它们另一个具有相似着色的图像。
我希望这会对你有所帮助,但你需要了解其运作方式,并在必要时进行评论,以解释最新情况。
祝你好运!