Skip to content

Commit

Permalink
Merge pull request #24 from yangguohao/task79
Browse files Browse the repository at this point in the history
【PaddlePaddle Hackathon】79 图片编码为量子态
QuLeaf authored Nov 5, 2021
2 parents 00b1396 + 6a601d1 commit 45eda40
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions paddle_quantum/utils.py
Original file line number Diff line number Diff line change
@@ -33,6 +33,7 @@
import matplotlib as mpl
from paddle_quantum import simulator
import matplotlib.animation as animation
import matplotlib.image

__all__ = [
"partial_trace",
@@ -58,6 +59,7 @@
"Hamiltonian",
"plot_state_in_bloch_sphere",
"plot_rotation_in_bloch_sphere",
"img_to_density_matrix",
]


@@ -1603,3 +1605,24 @@ def decompose(matrix):
pauli_form.append(pauli_site)

return pauli_form

def img_to_density_matrix(img_file):
r"""将图片编码为密度矩阵
Args:
img_file: 图片文件
Return:
rho:密度矩阵 ``
"""
img_matrix = matplotlib.image.imread(img_file)

#将图片转为灰度图
img_matrix = img_matrix.mean(axis=2)

#填充矩阵,使其变为[2**n,2**n]的矩阵
length = int(2**np.ceil(np.log2(np.max(img_matrix.shape))))
img_matrix = np.pad(img_matrix,((0,length-img_matrix.shape[0]),(0,length-img_matrix.shape[1])),'constant')
#trace为1的密度矩阵
rho = img_matrix@img_matrix.T
rho = rho/np.trace(rho)
return rho
16 changes: 16 additions & 0 deletions test_documents/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from paddle_quantum.utils import img_to_density_matrix
import paddle
import matplotlib.image
import numpy as np


img_file = '/home/aistudio/f1.jpeg'
rho = (img_to_density_matrix(img_file))

#半正定
w,_=np.linalg.eig(rho)
print(all(w>=0))
#迹为1
print(np.trace(rho))
#shape为[2**n,2**n]
print(rho.shape)

0 comments on commit 45eda40

Please sign in to comment.