0% found this document useful (0 votes)
8 views

project 2

The document contains Python code for generating and analyzing Flexible Representation of Quantum Images (FRQI) states. It includes functions to create random FRQI states, compute their statistics (mean, standard deviation, entropy), and visualize the results using histograms and bar charts. Additionally, it provides structured summaries of key points related to FRQI, including preparation complexity and experimental results.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

project 2

The document contains Python code for generating and analyzing Flexible Representation of Quantum Images (FRQI) states. It includes functions to create random FRQI states, compute their statistics (mean, standard deviation, entropy), and visualize the results using histograms and bar charts. Additionally, it provides structured summaries of key points related to FRQI, including preparation complexity and experimental results.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

[2]: import numpy as np

# Function to generate a random FRQI state for demonstration purposes


def generate_random_frqi_state(state_size):
return np.random.rand(state_size) + 1j * np.random.rand(state_size)

# Function to compute statistics on FRQI state


def compute_frqi_statistics(frqi_state):
# Compute mean and standard deviation
mean_value = np.mean(frqi_state)
std_dev = np.std(frqi_state)

# Compute entropy
entropy = -np.sum(np.abs(frqi_state) ** 2 * np.log2(np.abs(frqi_state) ** 2␣
,→+ 1e-10))

return mean_value, std_dev, entropy

# Example usage
state_size = 2 ** 8 # Adjust the size based on your actual FRQI state size
frqi_state = generate_random_frqi_state(state_size)

# Compute statistics
mean_value, std_dev, entropy = compute_frqi_statistics(frqi_state)

# Display the results


print("Mean Value:", mean_value)
print("Standard Deviation:", std_dev)
print("Entropy:", entropy)

Mean Value: (0.5056306058780464+0.4924584686981681j)


Standard Deviation: 0.4020889069495854
Entropy: 49.630194945953384

[6]: import numpy as np


import matplotlib.pyplot as plt

# Function to generate a random FRQI state for demonstration purposes


def generate_random_frqi_state(state_size):
return np.random.rand(state_size) + 1j * np.random.rand(state_size)

# Example usage
state_size = 2 ** 8 # Adjust the size based on your actual FRQI state size
frqi_state = generate_random_frqi_state(state_size)

# Create a histogram for the real and imaginary parts

1
plt.figure(figsize=(12, 6))

# Histogram for the real part


plt.subplot(1, 2, 1)
plt.hist(np.real(frqi_state), bins=50, color='blue', alpha=0.7)
plt.title('Histogram of Real Part')
plt.xlabel('Value')
plt.ylabel('Frequency')

# Histogram for the imaginary part


plt.subplot(1, 2, 2)
plt.hist(np.imag(frqi_state), bins=50, color='green', alpha=0.7)
plt.title('Histogram of Imaginary Part')
plt.xlabel('Value')
plt.ylabel('Frequency')

plt.tight_layout()
plt.show()

# Create a bar chart for mean, standard deviation, and entropy


mean_value, std_dev, entropy = np.mean(frqi_state), np.std(frqi_state), -np.
,→sum(np.abs(frqi_state) ** 2 * np.log2(np.abs(frqi_state) ** 2 + 1e-10))

labels = ['Mean', 'Std Dev', 'Entropy']


values = [mean_value, std_dev, entropy]

plt.figure(figsize=(8, 5))
plt.bar(labels, values, color=['orange', 'purple', 'red'])
plt.title('Statistics of FRQI State')
plt.ylabel('Value')

plt.show()

2
[ ]:

3
[1]: import numpy as np

# Key points
preparation_complexity = "polynomial"
qic_algorithm = "color-integrated controlled rotations"
processing_operators = np.array(["colors", "positions", "colors and positions"])
experiment_results = np.array(["storage and retrieval", "QIC compression", "line␣
,→detection"])

# Structured summary using NumPy arrays


summary_array = np.array([
["Study on Flexible Representation of Quantum Images (FRQI)", ""],
["Preparation Complexity", preparation_complexity],
["QIC Algorithm", qic_algorithm],
["Processing Operators", ', '.join(processing_operators)],
["Experiment Results", ', '.join(experiment_results)]
])

# Print the structured summary


for row in summary_array:
print(f"{row[0]:<25} {row[1]}")

Study on Flexible Representation of Quantum Images (FRQI)


Preparation Complexity polynomial
QIC Algorithm color-integrated controlled rotations
Processing Operators colors, positions, colors and positions
Experiment Results storage and retrieval, QIC compression, line detection

[12]: import numpy as np


import matplotlib.pyplot as plt

# Key points
preparation_complexity = "polynomial"
qic_algorithm = "color-integrated controlled rotations"
processing_operators = np.array(["colors", "positions", "colors and positions"])
experiment_results = np.array(["storage and retrieval", "QIC compression", "line␣
,→detection"])

# Structured summary using NumPy arrays


summary_array = np.array([
["Study on Flexible Representation of Quantum Images (FRQI)", ""],
["Preparation Complexity", preparation_complexity],
["QIC Algorithm", qic_algorithm],
["Processing Operators", ', '.join(processing_operators)],
["Experiment Results", ', '.join(experiment_results)]
])

1
# Extracting relevant information for plotting
labels = summary_array[:, 0]
values = summary_array[:, 1]

# Create a bar graph


fig, ax = plt.subplots()
bars = ax.bar(labels[1:], values[1:])

# Adding labels and title


ax.set_ylabel('Values')
ax.set_title('Structured Summary of Quantum Image Study')

# Adding values on top of the bars


for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, yval, round(yval, 2), ha='center',␣
,→va='bottom')

# Show the plot


plt.show()

[ ]:

2
[1]: import numpy as np

# Define the angles


theta = np.array([0, np.pi/4, np.pi/2, 3*np.pi/4])

# Define the state


state = 1/np.sqrt(2) * np.array([
[np.cos(theta[0])*np.array([1,0]), np.sin(theta[0])*np.array([1,0])],
[np.cos(theta[1])*np.array([1,0]), np.sin(theta[1])*np.array([1,0])],
[np.cos(theta[2])*np.array([1,0]), np.sin(theta[2])*np.array([1,0])],
[np.cos(theta[3])*np.array([1,0]), np.sin(theta[3])*np.array([1,0])]
])

# Print the state


print(state)

[[[ 7.07106781e-01 0.00000000e+00]


[ 0.00000000e+00 0.00000000e+00]]

[[ 5.00000000e-01 0.00000000e+00]
[ 5.00000000e-01 0.00000000e+00]]

[[ 4.32978028e-17 0.00000000e+00]
[ 7.07106781e-01 0.00000000e+00]]

[[-5.00000000e-01 -0.00000000e+00]
[ 5.00000000e-01 0.00000000e+00]]]

[2]: import numpy as np

def frqi_state(theta):
"""
Creates the FRQI state of a 2x2 image.

Args:
theta: A list of 4 angles, one for each pixel of the image.

Returns:
The FRQI state of the image as a numpy array.
"""
n = 2 # Number of qubits per pixel
m = 2**n # Number of basis states per pixel

# Create the basis states


basis_states = np.zeros((2**m, 2**m), dtype=complex)
for i in range(2**m):

1
binary_string = np.binary_repr(i, m).zfill(m)
for j in range(m):
basis_states[i, i] += (-1)**int(binary_string[j]) * 2**-(j + 1)

# Create the FRQI state


frqi_state = np.zeros((2**m, 2**m), dtype=complex)
for i in range(4):
frqi_state += np.outer(np.cos(theta[i])*basis_states[:, 0] + np.
,→sin(theta[i])*basis_states[:, 1], basis_states[i, :])

# Normalize the FRQI state


frqi_state /= np.sqrt(np.sum(np.abs(frqi_state)**2))

return frqi_state

# Example usage
theta = [np.pi/4, np.pi/3, np.pi/2, np.pi/6]
frqi_state = frqi_state(theta)
print(frqi_state)

[[4.73727255e-01+0.j 2.90312320e-01+0.j 3.00833123e-17+0.j


3.48117015e-01+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[4.10563621e-01+0.j 4.35790930e-01+0.j 4.25791403e-01+0.j
1.74187392e-01+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j

2
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j

3
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]]

[4]: import numpy as np

# Define the size of the image


width = 2
height = 2

# Define the angles for each pixel


theta = np.array([
[np.pi/4, np.pi/3],
[np.pi/6, np.pi/5]
])

# Create the FRQI state


frqi_state = np.zeros((2**height, 2**width), dtype=complex)
for i in range(2**height):
for j in range(2**width):
binary_i = np.binary_repr(i, width=height)[::-1]
binary_j = np.binary_repr(j, width=width)[::-1]
qubit_string = binary_i + binary_j
theta_i = theta[int(qubit_string[0])][int(qubit_string[1])]
# Access the real and imaginary parts separately
frqi_state[i, j] = np.cos(theta_i) + 1j * np.sin(theta_i)

# Print the FRQI state (real and imaginary parts)


print("Real part:")
print(frqi_state.real)

4
print("\nImaginary part:")
print(frqi_state.imag)

Real part:
[[0.70710678 0.70710678 0.70710678 0.70710678]
[0.8660254 0.8660254 0.8660254 0.8660254 ]
[0.5 0.5 0.5 0.5 ]
[0.80901699 0.80901699 0.80901699 0.80901699]]

Imaginary part:
[[0.70710678 0.70710678 0.70710678 0.70710678]
[0.5 0.5 0.5 0.5 ]
[0.8660254 0.8660254 0.8660254 0.8660254 ]
[0.58778525 0.58778525 0.58778525 0.58778525]]

[ ]:

5
[ ]: # Name: circuit.py
# Author: Isaac Cilia Attard
# Date: 04/10/2022
# Description: Implements the QFT circuit as detailed in the README.

"""NumPy packages"""
import numpy as np
from numpy import pi
"""Qiskit package"""
from qiskit import QuantumCircuit

def rotations(quantum_circuit, n): # Installs necessary rotation gates onto an␣


,→empty circuit

if n == 0: # Returns finalised generated circuit upon meeting the last qubit


return quantum_circuit
n -= 1 # Decrements current qubit to continue generating circuit
"""Generates gates for QFT"""
quantum_circuit.h(n) # Hadamard gate application
for qubit in range(n):
quantum_circuit.cp(pi/2**(n-qubit), qubit, n) # Controlled-phase gate␣
,→application

rotations(quantum_circuit, n) # Utilises recursion to rotate the rest of the␣


,→n-1 qubits

def swap(quantum_circuit, n): # Swaps qubits in order to match QFT definition


for qubit in range(n//2):
quantum_circuit.swap(qubit, n-qubit-1)
return quantum_circuit

def qft(quantum_circuit, n): # Generalised QFT-circuit generator based on␣


,→mathematical derivation

"""Generation is split into two functions"""


rotations(quantum_circuit, n)
swap(quantum_circuit, n)
return quantum_circuit # Returns finalised circuit

[ ]: # Name: encoder.py
# Author: Isaac Cilia Attard
# Date: 07/10/2022
# Description: Encodes classical bits onto a quantum circuit.

"""NumPy packages"""
import numpy as np
"""OpenCV package"""
import cv2

1
"""IBM Qiskit package"""
from qiskit import QuantumCircuit
"""QFT circuit generator"""
from circuit import qft

def image_to_binary(path): # Converts image to binary and presents data in a␣


,→flattened NumPy array

image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)


image_array = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)[1]
return image_array.flatten(order='C') # Returns flattened image pixel values␣
,→in a row-wise manner

def basis_encode(array): # Encodes array into a quantum circuit via␣


,→computational basis states

quantum_circuit = QuantumCircuit(array.size) # Creates a new circuit with␣


,→enough qubits to hold the image

n = 0 # Begins encoding from 0th qubit


for bit in array:
if bit == 255: # Applies Pauli-X gate to qubit to represent coloured␣
,→value

quantum_circuit.x(n)
elif bit == 0:
pass
n += 1 # Continues to encode the next qubit
return quantum_circuit # Returns the finalised quantum circuit

[ ]: # Name: main.py
# Author: Isaac Cilia Attard
# Date: 08/10/2022
# Description: Offers an image to the QFT circuit and displays the results.

"""Qiskit packages"""
from qiskit import Aer
from qiskit.visualization import plot_bloch_multivector
"""Matplotlib package"""
import matplotlib.pyplot as plt
"""Circuit and encoder packages"""
from circuit import qft
from encoder import basis_encode, image_to_binary

circuit = basis_encode(image_to_binary("test.png")) # Encodes an image onto a␣


,→quantum circuit

simulator = Aer.get_backend("aer_simulator") # Qiskit Aer simulator instantiation

"""Computational basis qubits"""


qc_init = circuit.copy()
qc_init.save_statevector()

2
statevector = simulator.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)

"""Fourier basis qubits"""


qft(circuit, image_to_binary("test.png").size) # Applies QFT to encoded image
circuit.save_statevector()
statevector = simulator.run(circuit).result().get_statevector()
plot_bloch_multivector(statevector)

circuit.draw(output='mpl') # Renders circuit before showing it


plt.show()

3
[ ]: from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
from qiskit import execute, Aer, BasicAer
import numpy as np
import random
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.datasets import mnist
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error,␣
,→mutual_info_score, r2_score

from resizeimage import resizeimage


from PIL import Image

def margolus(circ, t, c0, c1):


circ.ry(np.pi/4,t)
circ.cx(c0, t)
circ.ry(np.pi/4,t)
circ.cx(c1, t)
circ.ry(-np.pi/4,t)
circ.cx(c0, t)
circ.ry(-np.pi/4,t)

def rccx(circ, t, c0, c1):


circ.h(t)
circ.t(t)
circ.cx(c0, t)
circ.tdg(t)
circ.cx(c1, t)
circ.t(t)
circ.cx(c0, t)
circ.tdg(t)
circ.h(t)

def rcccx(circ, t, c0, c1, c2):


circ.h(t)
circ.t(t)
circ.cx(c0, t)
circ.tdg(t)
circ.h(t)
circ.cx(c1, t)
circ.t(t)

1
circ.cx(c2, t)
circ.tdg(t)
circ.cx(c1, t)
circ.t(t)
circ.cx(c2, t)
circ.tdg(t)
circ.h(t)
circ.t(t)
circ.cx(c0, t)
circ.tdg(t)
circ.h(t)

def ccry(circ, angle, t, c0, c1):


circ.cu3(angle/2, 0, 0, c1, t)
circ.cx(c1, c0)
circ.cu3(-angle/2, 0, 0, c0, t)
circ.cx(c1, c0)
circ.cu3(angle/2, 0, 0, c0, t)

def mary(circ, angle, t, c0, c1):


circ.ry(angle/4,t)
circ.cx(c0, t)
circ.ry(-angle/4,t)
circ.cx(c1, t)
circ.ry(angle/4,t)
circ.cx(c0, t)
circ.ry(-angle/4,t)
circ.cx(c1, t)

def cccry(circ, angle, t, a, c0, c1, c2):


margolus(circ, a, c1, c2)
mary(circ, angle, t, a, c0)
margolus(circ, a, c1, c2)

def mary_4(circ, angle, t, c0, c1, c2):


circ.h(t)
circ.t(t)
circ.cx(c0,t)
circ.tdg(t)
circ.h(t)
circ.cx(c1,t)
circ.rz(angle/4,t)
circ.cx(c2,t)
circ.rz(-angle/4,t)
circ.cx(c1,t)
circ.rz(angle/4,t)

2
circ.cx(c2,t)
circ.rz(-angle/4,t)
circ.h(t)
circ.t(t)
circ.cx(c0,t)
circ.tdg(t)
circ.h(t)

def mary_8(circ, angle, t, c0, c1, c2, c3, c4, c5, c6):
circ.h(t)
circ.t(t)
rccx(circ, t, c0, c1)
circ.tdg(t)
circ.h(t)
rccx(circ, t, c2, c3)
circ.rz(angle/4,t)
rcccx(circ, t, c4, c5, c6)
circ.rz(-angle/4,t)
rccx(circ, t, c2, c3)
circ.rz(angle/4,t)
rcccx(circ, t, c4, c5, c6)
circ.rz(-angle/4,t)
circ.h(t)
circ.t(t)
rccx(circ, t, c0, c1)
circ.tdg(t)
circ.h(t)

def c10ry(circ, angle, bin, target, anc, controls):


# c10mary(qc, 2 * x_train[img_num][i], format(i, '010b'), 0, 1, [i for i in␣
,→range(2,12)])

print(bin)
clist = []

for i in bin:
clist.append(int(i))

for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])

margolus(circ, anc, controls[0], controls[1])


circ.x(controls[0])
circ.x(controls[1])
margolus(circ, controls[1], controls[2], controls[3])
circ.x(controls[2])

3
circ.x(controls[3])
margolus(circ, controls[3], controls[4], controls[5])
circ.x(controls[4])
circ.x(controls[5])

margolus(circ, controls[5], controls[8], controls[9])


margolus(circ, controls[4], controls[6], controls[7])
margolus(circ, controls[2], controls[4], controls[5])
margolus(circ, controls[0], controls[2], controls[3])

mary_4(circ, angle, target, anc, controls[0], controls[1])

margolus(circ, controls[0], controls[2], controls[3])


margolus(circ, controls[2], controls[4], controls[5])
margolus(circ, controls[4], controls[6], controls[7])
margolus(circ, controls[5], controls[8], controls[9])

circ.x(controls[5])
circ.x(controls[4])
margolus(circ, controls[3], controls[4], controls[5])
circ.x(controls[3])
circ.x(controls[2])
margolus(circ, controls[1], controls[2], controls[3])
circ.x(controls[1])
circ.x(controls[0])
margolus(circ, anc, controls[0], controls[1])

for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])

def c10mary(circ, angle, bin, target, anc, controls):

# c10mary(qc, 2 * x_train[img_num][i], format(i, '010b'), 0, 1, [i for i␣


,→in range(2,12)])

clist = []

for i in bin:
clist.append(int(i))
# print("angle", angle)
# print("clist - bin",clist)

for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])

rccx(circ, anc, controls[4], controls[5])

4
# circuit_drawer(circ,output='mpl', filename='my_circuit_rccx.png')
circ.x(controls[4])
circ.x(controls[5])
rccx(circ, controls[4], controls[6], controls[7])
rccx(circ, controls[5], controls[8], controls[9])

mary_8(circ, angle, target, anc, controls[0], controls[1], controls[2],␣


,→controls[3], controls[4], controls[5])

rccx(circ, controls[5], controls[8], controls[9])


rccx(circ, controls[4], controls[6], controls[7])
circ.x(controls[5])
circ.x(controls[4])
rccx(circ, anc, controls[4], controls[5])

for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])
# for i in range(len(clist)):
# circ.x(controls[i])

def image_normalization(image):
image = resizeimage.resize_cover(image, [32, 32])
w, h = 32, 32
image = np.array([[image.getpixel((x,y))[0] for x in range(w)] for y in␣
,→range(h)])

# 2-dimentional data convert to 1-dimentional array


image = image.flatten()
# change type
image = image.astype('float64')
# Normalization(0~pi/2)
image /= 255.0
generated_image = np.arcsin(image)

return generated_image

if __name__ == '__main__':
# (x_train, y_train), (x_test, y_test) = mnist.load_data()
# img_num = 1

# #show original image


# plt.imshow(x_train[img_num], cmap='gray')

5
# #plt.savefig('mnistimg'+str(img_num)+'.png')
# plt.show()

# # 2-dimentional data convert to 1-dimentional array


# x_train = x_train.reshape(60000, 784)
# # change type
# x_train = x_train.astype('float64')
# # Normalization(0~pi/2)
# x_train /= 255.0
# x_train = np.arcsin(x_train)
x_train=image_normalization(Image.open("cat.png").convert('LA'))

backends = Aer.backends()

#print("Aer backends:",backends)

qubit = 12
qc = QuantumCircuit(qubit,qubit)

# apply hadamard gates


qc.h(range(2,qubit))
# image1 = image_normalization(image1)

# apply c10Ry gates (representing color data)


for i in range(len(x_train)):
if x_train[i] != 0:
c10mary(qc, 2 * x_train[i], format(i, '010b'), 0, 1, [i␣
,→for i in range(2,12)])

# qc.x(range(2,qubit))
qc.measure(range(qubit),range(qubit))

backend_sim = Aer.get_backend('qasm_simulator')
#print(qc.depth())
numOfShots = 1000000
result = execute(qc, backend_sim, shots=numOfShots).result()
#circuit_drawer(qc).show()
#plot_histogram(result.get_counts(qc))

print(result.get_counts(qc))

# generated image
genimg = np.array([])

#### decode

6
for i in range(len(x_train)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'01']/numOfShots)])

except KeyError:
genimg = np.append(genimg,[0.0])

# inverse nomalization
genimg *= 32.0 * 255.0
x_train = np.sin(x_train)
x_train *= 255.0

# convert type
genimg = genimg.astype('int')

# back to 2-dimentional data


genimg = genimg.reshape((32,32))

plt.imshow(genimg, cmap='gray', vmin=0, vmax=255)


# plt.savefig('gen_'+str(img_num)+'.png')
plt.show()

[ ]: from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute


from qiskit.aqua.circuits.fourier_transform_circuits import␣
,→FourierTransformCircuits

from math import pi


from qiskit import Aer

def quantum_adder(circuit, epsilon):


qubits = circuit.qubits
n_qubits = circuit.n_qubits
FourierTransformCircuits.construct_circuit(circuit, qubits)
for i in range(n_qubits):
circuit.u1(float(2 * pi * epsilon)/2**(i + 1), qubits[n_qubits - i - 1])
FourierTransformCircuits.construct_circuit(circuit, qubits, inverse=True)

def quantum_rotate_image(circuit): #gives you the quantum state where you␣


,→have to measure the ancilla and obtain 0

for i in circuit.qubits:
circuit.x(i)

def quantum_edge_detection(circuit): #gives you the quantum state where␣


,→you have to measure the ancilla and obtain 0

qubits = circuit.qubits
ancilla = qubits[0]
circuit.h(ancilla)
quantum_adder(circuit, -1)

7
circuit.h(ancilla)
circuit.x(ancilla)

# circuit.measure(ancilla, clbit)

# backend = Aer.get_backend('qasm_simulator')
# job_sim = execute(circuit, backend)
# sim_result = job_sim.result()

# print(sim_result.get_counts(circuit))

[ ]: import utils
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram, plot_gate_map,␣
,→plot_circuit_layout

from qiskit import execute, Aer, BasicAer


from qiskit.providers.aer.noise import NoiseModel
import numpy as np
import matplotlib.pyplot as plt
from resizeimage import resizeimage
from PIL import Image, ImageOps
import frqi
import quantum_edge_detection as qed
# import quantum_edge_detection as qed

# Insert API key generated after registring in IBM Quantum Experience


# IBMQ.save_account('API KEY')

IBMQ.load_account()
provider = IBMQ.get_provider( group='open', project='main')

# dimensions of the image


size=32

#target image
image=utils.get_Cat_image()

8
#normalized image
normalized_image=utils.image_normalization(image,32,True)

#get target image pixel values for comparison with output image
img_arr=utils.get_image_pixel_value(image,32)

# initialize qubits and classical registers for building the circuit


anc = QuantumRegister(1, "anc")
img = QuantumRegister(11, "img")
anc2 = QuantumRegister(1, "anc2")
c = ClassicalRegister(12)

# create circuit
qc = QuantumCircuit(anc, img, anc2, c)

# apply hadamard gates


for i in range(1, len(img)):
qc.h(img[i])

# frqi circuit from https://github.com/Shedka/citiesatnight


for i in range(len(normalized_image)):
if normalized_image[i] != 0:
frqi.c10mary(qc, 2 * normalized_image[i], format(i, '010b'),␣
,→img[0], anc2[0], [img[j] for j in range(1,len(img))])

#rotate the image 180 deg


# qed.quantum_rotate_image(qc)

#Edge Detection
# qed.quantum_edge_detection()

qc.measure(img, c[1:12])
print(qc.depth())
numOfShots = 1000000

#To add noise on the simulation UNCOMMENT BELOW LINES

# backend = provider.get_backend('ibmq_16_melbourne')
# noise_model = NoiseModel.from_backend(backend)
# # Get coupling map from backend
# coupling_map = backend.configuration().coupling_map
# # Get basis gates from noise model
# basis_gates = noise_model.basis_gates

# To run without noise UNCOMMENT BELOW LINES

9
# result = execute(qc, Aer.get_backend('qasm_simulator'),␣
,→shots=numOfShots,coupling_map=coupling_map,

# basis_gates=basis_gates,
# noise_model=noise_model).result()

# To run without noise UNCOMMENT BELOW LINES


result = execute(qc, Aer.get_backend('qasm_simulator'), shots=numOfShots).
,→result()

# Image retrieval from quantum state to pixels

genimg = np.array([])

#### decode
for i in range(len(normalized_image)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'10']/numOfShots)])

except KeyError:
genimg = np.append(genimg,[0.0])

# inverse nomalization
genimg *= size * 255.0
# genimg = np.sin(genimg)

same,notSame= utils.get_count_of_pixel(img_arr,genimg)
print(same,notSame)
percentage= (same/1024)*100
print ("Total image recovered "+ str(percentage))

# convert type
genimg = genimg.astype('int')
genimg = genimg.reshape((size,size))
plt.imshow(genimg, cmap='gray', vmin=0, vmax=255)
plt.savefig('Result'+'.png')
plt.show()

[ ]: # frqi circuit from https://github.com/Shedka/citiesatnight

import utils
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer

10
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram, plot_gate_map,␣
,→plot_circuit_layout

from qiskit import execute, Aer, BasicAer


from qiskit.providers.aer.noise import NoiseModel
import numpy as np
import matplotlib.pyplot as plt
from resizeimage import resizeimage
from PIL import Image, ImageOps
import frqi
# import quantum_edge_detection as qed

# Insert API key generated after registring in IBM Quantum Experience


# IBMQ.save_account('API KEY')

IBMQ.load_account()
provider = IBMQ.get_provider( group='open', project='main')

# dimensions of the image


size=32

#target image
images=utils.get_Cat_320_image()

# New blank image


new_im = Image.new('RGB', (320, 320))

for k in range(10):
for j in range(10):
normalized_image=utils.
,→large_image_normalization(images,32+(32*k),32+(32*j))

genimg= np.array([])
anc = QuantumRegister(1, "anc")
img = QuantumRegister(11, "img")
anc2 = QuantumRegister(1, "anc2")
c = ClassicalRegister(12)
qc = QuantumCircuit(anc, img, anc2, c)

for i in range(1, len(img)):


qc.h(img[i])

11
for i in range(len(normalized_image)):
if normalized_image[i] != 0:
frqi.c10mary(qc, 2 * normalized_image[i], format(i,␣
,→'010b'), img[0], anc2[0], [img[j] for j in range(1,len(img))])

qc.measure(img, c[1:12])
print(qc.depth())
numOfShots = 1000000
result = execute(qc, Aer.get_backend('qasm_simulator'),␣
,→shots=numOfShots).result()

for i in range(len(normalized_image)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'10']/numOfShots)])

except KeyError:
genimg = np.append(genimg,[0.0])

genimg *= 32.0 * 255.0


genimg = genimg.astype('int')
genimg = genimg.reshape((32,32))
im=Image.fromarray(genimg)

new_im.paste(im,(32*k,32*j))
new_im.show()
new_im.save('Result_320.png')

[ ]: import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from resizeimage import resizeimage
from PIL import Image, ImageOps

def get_MNIST_data():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
return x_train

def get_Cat_320_image():
return Image.open("cat_320.png").convert('LA')

def get_Cat_image():
return Image.open("cat.png").convert('LA')

def large_image_normalization(images,w,h):
image=np.array([])

for y in range(h-32,h):

12
for x in range(w-32,w):
image=np.append(image,images.getpixel((x,y))[0])
genimg = image.reshape((32,32))
image = image.flatten()
# change type
image = image.astype('float64')
# Normalization(0~pi/2)
image /= 255.0
generated_image=image
# generated_image = np.arcsin(image)
print(generated_image)
image=images
return generated_image

def image_normalization(image,size,show):
image = resizeimage.resize_cover(image, [size, size])
w, h = size, size
image = np.array([[image.getpixel((x,y))[0] for x in range(w)] for y in␣
,→range(h)])

# display the image


if show:
genimg = image.reshape((size,size))
plt.imshow(genimg, cmap='gray', vmin=0, vmax=255)
plt.show()

image = image.flatten()
image = image.astype('float64')
image /= 255.0
generated_image = np.arcsin(image)
# print(generated_image)
return generated_image

def generate_image(size):
w, h = size, size
data = np.zeros((h, w, 3), dtype=np.uint8)
w_bound=int(w/2)
h_bound=int(h/2)
data[0:w_bound, 0:h_bound] = [255, 0, 0] # red patch in upper left
data[0:w_bound, h_bound+1:h] = [0, 255, 0] # red patch in upper left
data[w_bound+1:w, 0:h_bound] = [0, 0, 255] # red patch in upper left
data[w_bound+1:w, h_bound+1:h] = [128, 128, 128] # red patch in upper left

imgq = Image.fromarray(data, 'RGB')


imgq.save('my.png')

13
return imgq.convert('LA')

def get_image_pixel_value(image,size):
img_arr= np.array([[image.getpixel((x,y))[0] for x in range(size)] for y in␣
,→range(size)])

img_arr = img_arr.flatten()
return img_arr

def get_count_of_pixel(arr1,arr2):
same=0
notsame=0
for i in range(len(arr1)):
if arr1[i]==arr2[i]:
same+=1
else:
notsame+=1
return (same,notsame)

14
One of the most interesting area where Quantum science and technology is
being utilized is Quantum Image Processing. With a multitude of advances in
technology, image processing has become an extensively researched upon area of
technology. It is being employed in various different disciplines and areas of
research. Facial recognition, automated vehicles, image Photoshop and numerous
other techniques use image processing as their basis. Utilizing Quantum
technology in image processing is what Quantum image processing is all about. As
is evident until now, quantum image processing will be a lot more efficient in terms
of speed and time than its classical counterpart. It will also prove to be extremely
useful for simple day to day applications like simple face recognition on a mobile
phone or criminal detection at a police station, but all of this might be possible in a
fraction of time and with much less error than is now using classical techniques.
Image compression, edge detection, image storage, image retrieval, binary image
line detection are just some of the tasks achievable by quantum image processing
[1, 4].

In order to carry out Quantum Image Processing, the image must first be
transformed into its quantum counterpart known as the quantum image. This state
can be achieved by a number of different processes like FRQI (Flexible
Representation of Quantum Image), NEQR (Novel Enhanced Quantum
Representation), QBIP (Quantum Boolean Image Processing) and a variety of
others [6]. Here we discusses the FRQI technique in detail. The FRQI state
represents the classical images, after a transformation, as quantum images on a
quantum computer in a normalized state. This state carries the information about
the colours in an image and their respective positions. It is quite an efficient
method for the preparation of an image on which various different quantum image
processing algorithms can be applied to achieve desired results. Not only does
FRQI provide a representation to images but can also prove to be extremely useful
for the exploration of other tasks performed by the quantum computers regarding
image processing [1, 2]. Preparing this state requires a polynomial number of
simple operations and gates [2, 4]. We work with a 2x2 image i.e. 4 pixels image,
where the color and its position is encoded in the FRQI state as shown below,

, (1)

. (2)

Mathematical Formulations
The FRQI state contains coded information in the form of colour and its related
pixel position as shown below. FRQI state is prepared through a unitary
transformation which has two steps. First applying the hadamard transform H =
I⊗H⊗2, where I is the 2D identity matrix and H is the hadamard gate, on |0⟩⊗3,
producing the state |H⟩,
. (3)
State |0⟩ is initialised on all three qubits and hadamard gate is applied on the first
two, creating superposition. The third qubit is our ancillary qubit. In the second
step, controlled rotations are applied on the |H⟩ state as defined by,

. (4)

where

The controlled rotations are applied in succession correspondimg to the


number of pixels, which in our case is 4. This corresponds to a unitary operation R
defined as,

. (5)
Equation ’(1)’ is our state obtained after applying the hadamard transform. Now,
the controlled rotation operators are applied in succession as follows.

(6)

!
!

In above equation, the second term vanishes and are just numeric
representation of two qubit states in Zeeman basis,

1. |0⟩ = |00⟩

2. |1⟩ = |01⟩

3. |2⟩ = |10⟩

4. |3⟩ = |11⟩.

Hence, the FRQI state achieved is,


[ ]: import qiskit as qk
from qiskit import Aer,execute
from math import pi

qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State

qc.h(qr[0])
qc.h(qr[1])

# Circuit for I(theta) starts here


qc.x(qr[0])
qc.x(qr[1])

#pi/4=0.7853
qc.cu3(0.7853,0,0,qr[0],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(-0.7853,0,0,qr[1],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(0.7853,0,0,qr[0],qr[2])

#pi/12=0.2617
qc.x(qr[1])

qc.cu3(0.2617,0,0,qr[0],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(-0.2617,0,0,qr[1],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(0.2617,0,0,qr[0],qr[2])

#pi/6=0.5234

1
qc.x(qr[0])
qc.x(qr[1])

qc.cu3(0.5234,0,0,qr[0],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(-0.5234,0,0,qr[1],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(0.5234,0,0,qr[0],qr[2])

#pi/16=0.1963
qc.x(qr[1])

qc.cu3(0.1963,0,0,qr[0],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(-0.1963,0,0,qr[1],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(0.1963,0,0,qr[0],qr[2])

qc.barrier(qr)

qc.measure(qr,cr)

# In[41]:

2
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()

# In[42]:

counts = result_sim.get_counts(qc)
print(counts)

[ ]: from PIL import Image


import numpy as np
from math import pi, floor

"""
img = Image.new('RGB', (60, 30), color = 'red')
img.save('pil_red.png')
"""
# Create a NumPy array, which has four elements. The top-left should be pure␣
,→red, the top-right should be pure blue, the bottom-left should be pure green,␣

,→and the bottom-right should be yellow

def double_size(im):

rows = len(im)
cols = len(im[0])

half_r = rows/2
half_c = cols/2

new_im = np.zeros(((rows * 2, cols * 2, 3)))

r = im[0]
first = r[0]
second = r[int(cols/2)]

for i in range(rows):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]

r = im[int(rows/2)]
first = r[0]
second = r[int(cols/2)]

3
for i in range(rows, rows * 2):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]

return new_im

def make_image(pixels):

# Create a PIL image from the NumPy array


image = Image.fromarray(pixels.astype('uint8'), 'RGB')

# Save the image


#image.save('image.png')
image.show()

def get_smallest():

pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255,␣
0]]])
,→

return pixels

"""
pixels = np.array([[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255,␣
,→0], [0, 255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]]])

"""
"""

4
def rgb_to_theta(rgb):

r, g, b = rgb
theta = (pi/2) * ((r/2) + (g/4) + (b/8))
#print("Theta is ", theta)
return theta

def theta_to_rgb(theta):

r = floor(theta/(pi/4))

theta = theta - r*(pi/4)

g = floor(theta/(pi/8))

theta = theta - g*(pi/8)

b = floor(theta/(pi/16))
print("rgb = ", [r, g, b])

def test_it():

list = []
for i in range(2):
for j in range(2):
for k in range(2):
list.append([i, j, k])

i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)
"""

def rgb_to_theta(rgb):

r, g, b = rgb
theta = (pi/2) * ((r/256) + (g/(256**2)) + (b/256**3))
print("Theta is ", theta)
return theta

def theta_to_rgb(theta):

r = floor(theta/((pi/2) * (1/256)))

5
theta = theta - r*((pi/2) * (1/256))
print("After R, theta is ", theta)

g = floor(theta/((pi/2) * (1/256**2)))
theta = theta - g*((pi/2) * (1/256**2))
print("After G, theta is ", theta)

b = floor(theta/((pi/2) * (1/256**3)))

print("rgb = ", [r, g, b])

def test_it():

list = []
for i in range(5):
for j in range(5):
for k in range(5):
list.append([i, j, k])

i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)

=========================================

# coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi
#pi = 3.14159

def run():

qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State


qc.h(qr[0])
qc.h(qr[1])

6
# Circuit for I(theta) starts here
#qc.x(qr[0])
#qc.x(qr[1])

angles = [pi/2, 0, pi/2, 0]


#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[0],qr[2])

###
qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=10000)
result_sim = job_sim.result()

# In[42]:

counts = result_sim.get_counts(qc)
print(counts)
###

"""

#pi/12=0.2617

qc.x(qr[1])

qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])

#pi/6=0.5234

qc.x(qr[0])
qc.x(qr[1])

qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])

7
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])

#pi/16=0.1963

qc.x(qr[1])

qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])

qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=10000)
result_sim = job_sim.result()

# In[42]:

counts = result_sim.get_counts(qc)
print(counts)
"""
======================

def probs(results):

angles = []
if ("000" in results):
prob = results["000"]/num_shots
# to get the angle back cos^-1(sqrt(probability))
angles.append(acos(sqrt(4 *prob)))
else:
angles.append(pi/2)

if ("001" in results):
probs.append(results["001"]/num_shots)
else:
probs.append(0.)

if ("010" in results):
probs.append(results["010"]/num_shots)
else:

8
probs.append(0.)

if ("011" in results):
probs.append(results["011"]/num_shots)
else:
probs.append(0.)

print(probs)

========
if ("000" in results):
prob = results["000"]/num_shots
# to get the angle back cos^-1(sqrt(4 * probability))
angles.append(acos(sqrt(4 *prob)))
else:
angles.append(pi/2)

#converting from rgb to theta and vice versa in degrees


====================
# function to convert an rgb value into an angle, theta
def rgb_to_theta(rgb):

r, g, b = rgb
# storing the angle in degrees instead of radians
theta = (90) * ((r/256) + (g/(256**2)) + (b/256**3))
return theta

# function to convert the angle theta back into an rgb value


def theta_to_rgb(theta):

# recovering the value of r


r = floor(theta/(90/256))
# subtracting from theta to get the angle to be in the first region of␣
,→the quadrant

theta = theta - r*(90/256)


# now that the angle is in the first region, can multiply to get it to␣
,→the proper region for the g value

theta *= 256

# recovering the value of g


g = floor(theta/(90/256))
theta = theta - g*(90/256)
theta *= 256

b = floor(theta/(90/256))

9
return [r,g,b]

"""
pixels = np.array([[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255,␣
,→0], [0, 255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],

[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]]])

"""

"""
# I can put this into a for loop if I need to.
# probs for 1st pixel
if ("000" in results):
prob["000"] = results["000"]/num_shots
else:
prob["000"] = 0.

if ("100" in results):
prob["100"] = results["100"]/num_shots
else:
prob["100"] = 0.

# probs for 2nd pixel


if ("001" in results):
prob["001"] = results["001"]/num_shots
else:
prob["001"] = 0.

if ("101" in results):
prob["101"] = results["101"]/num_shots
else:
prob["101"] = 0.

# probs for 3rd pixel

10
if ("010" in results):
prob["010"] = results["010"]/num_shots
else:
prob["010"] = 0.

if ("110" in results):
prob["110"] = results["110"]/num_shots
else:
prob["110"] = 0.

# probs for 4th pixel


if ("011" in results):
prob["011"] = results["011"]/num_shots
else:
prob["011"] = 0.

if ("111" in results):
prob["111"] = results["111"]/num_shots
else:
prob["111"] = 0.

angles = []
# now need to recover the angles
zero_prob = prob["000"]/(prob["000"] + prob["100"])
angles.append(acos(sqrt(zero_prob)))

zero_prob = prob["001"]/(prob["001"] + prob["101"])


angles.append(acos(sqrt(zero_prob)))

zero_prob = prob["010"]/(prob["010"] + prob["110"])


angles.append(acos(sqrt(zero_prob)))

zero_prob = prob["011"]/(prob["011"] + prob["111"])


angles.append(acos(sqrt(zero_prob)))
"""

===========================

qc.ccx(qr[0], qr[1], qr[4])


qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[3], qr[5], qr[6])

qc.cu3(angles[0],0,0,qr[6],qr[7])

qc.ccx(qr[3], qr[5], qr[6])


qc.ccx(qr[2], qr[4], qr[5])

11
qc.ccx(qr[0], qr[1], qr[4])

===========================
pixels = np.array([[[250, 5, 5], [5, 250, 5], [5, 5, 250], [250, 250, 5]],
[[250, 5, 250], [5, 250, 250], [100, 50, 5], [5, 100, 50]],
[[100, 100, 100], [100, 150, 200], [200, 100, 150], [150, 200,␣
,→150]],

[[75, 180, 105], [180, 105, 75], [105, 180, 75], [128, 128,␣
,→128]]])

===========================

def get_xs():

chars = ["0","1"]
vals = []

for i in chars:
for j in chars:
for k in chars:
for l in chars:
vals.append(i + j + k + l)

total = []
for i in range(16):

x_vals = []
word = vals[i]
for j in range(4):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')

total.append(x_vals)

for k in range(16):
for q in range(4):
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(4):
if (r != q):
new_val.
,→append(vals[k][r])

else:

12
new_val.
append('1')
,→

vals[k] = new_val
else:
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→

else:
new_val.
append('0')
,→

vals[k] = new_val

print("================ ", i, " =================")


print(vals)

print(total)

[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi, sqrt, acos
from image_testing import r_num, g_num, b_num

num_shots = 100000

def probs(results):

prob = {}

chars = ["0", "1"]


for c in chars:
for d in chars:
for e in chars:
state = c + d + e
if (state in results):
prob[state] = results[state]/num_shots
else:
prob[state] = 0.

angles = []
for c in chars:
for d in chars:
zero = "0" + c + d
one = "1" + c + d

13
zero_prob = prob[zero]/(prob[zero] + prob[one])
angles.append(acos(sqrt(zero_prob)))

return angles

def probs4(results):

prob = {}

chars = ["0", "1"]


for c in chars:
for d in chars:
for e in chars:
for f in chars:
for g in chars:
state = c + "000" + d + e + f + g
if (state in results):
prob[state] =␣
,→results[state]/num_shots

else:
prob[state] = 0.

angles = []
for c in chars:
for d in chars:
for e in chars:
for f in chars:
zero = "0000" + c + d + e + f
one = "1000" + c + d + e + f
zero_prob = prob[zero]/(prob[zero] +␣
,→prob[one])

angles.append(acos(sqrt(zero_prob)))

return angles

def run(angles):

qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State


qc.h(qr[0])
qc.h(qr[1])

# Circuit for I(theta) starts here

14
qc.x(qr[0])
qc.x(qr[1])

#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[1],qr[2])

#pi/12=0.2617
qc.x(qr[0])

qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[1],qr[2])

#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])

qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[1],qr[2])

#pi/16=0.1963
qc.x(qr[0])

qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[1],qr[2])

qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()

# In[42]:

15
counts = result_sim.get_counts(qc)

new_angles = probs(counts)

return new_angles

def run_4(angles):

# can just pass in the same angles as I did for 2x2. No need to double␣
them.
,→

for i in range(len(angles)):
angles[i] = 2 * angles[i]

# we are including 3 ancilla qubits


qr =qk.QuantumRegister(8)
cr = qk.ClassicalRegister(8)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State


qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])

# angle to manipulate the colors by

for i in range(16):

qc.x(qr[0])

if (i % 4 == 2):
qc.x(qr[1])

if (i == 0 or i == 8):
qc.x(qr[1])
qc.x(qr[2])
qc.x(qr[3])

if (i == 4 or i == 12):
qc.x(qr[1])
qc.x(qr[2])

qc.ccx(qr[0], qr[1], qr[4])


qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[3], qr[5], qr[6])

16
qc.cu3(angles[i],0,0,qr[6],qr[7])

qc.ccx(qr[3], qr[5], qr[6])


qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[0], qr[1], qr[4])

"""
################
# pixel shifting

#C3not
qc.ccx(qr[0], qr[1], qr[4])
qc.ccx(qr[2], qr[4], qr[5])

qc.cx(qr[5], qr[3])

qc.ccx(qr[2], qr[4], qr[5])


qc.ccx(qr[0], qr[1], qr[4])

#C2not
qc.ccx(qr[0], qr[1], qr[2])

#CNOT
qc.cx(qr[0], qr[1])

#NOT
qc.x(qr[0])

################
"""

qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()

# In[42]:
counts = result_sim.get_counts(qc)

#print(counts)

new_angles = probs4(counts)

return new_angles

17
"""
def test():

for i in range(16):

angles = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
angles[i] = pi/2

run_4(angles)
#print("==============\n", i, "\n==============")

break
"""

def get_xs():

chars = ["0","1"]
vals = []

for i in chars:
for j in chars:
for k in chars:
for l in chars:
for m in chars:
for n in chars:
vals.append(i + j + k +␣
,→l + m + n)

total = []
for i in range(64):

x_vals = []
word = vals[i]
for j in range(6):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')

total.append(x_vals)

for k in range(64):
for q in range(6):

18
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(6):
if (r != q):
new_val.
append(vals[k][r])
,→

else:
new_val.
append('1')
,→

vals[k] = new_val
else:
new_val = []
for r in range(6):
if (r != q):
new_val.
append(vals[k][r])
,→

else:
new_val.
append('0')
,→

vals[k] = new_val

#print("================ ", i, " =================")


#print(vals)

print(total)

[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute

pi = 3.14

def run():
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State

qc.h(qr[0])
qc.h(qr[1])

19
# Circuit for I(theta) starts here
qc.x(qr[0])
qc.x(qr[1])

angles = [pi/2, 0, pi/4, pi/6]


#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(-angles[0],0,0,qr[1],qr[2])

qc.cx(qr[0],qr[1])

qc.cu3(angles[0],0,0,qr[0],qr[2])

#pi/12=0.2617

qc.x(qr[1])

qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])

#pi/6=0.5234

qc.x(qr[0])
qc.x(qr[1])

qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])

#pi/16=0.1963

qc.x(qr[1])

qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])

20
qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()

# In[42]:

counts = result_sim.get_counts(qc)
print(counts)

[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi, sqrt, acos
from image_testing import r_num, g_num, b_num

num_shots = 100000000

def probs(results):

prob = {}

chars = ["0", "1"]


for c in chars:
for d in chars:
for e in chars:
state = c + d + e
if (state in results):
prob[state] = results[state]/num_shots
else:
prob[state] = 0.

angles = []
for c in chars:
for d in chars:
zero = "0" + c + d
one = "1" + c + d
zero_prob = prob[zero]/(prob[zero] + prob[one])
angles.append(acos(sqrt(zero_prob)))

return angles

def probs4(results):

21
prob = {}

chars = ["0", "1"]


for c in chars:
for d in chars:
for e in chars:
for f in chars:
for g in chars:
state = c + "000" + d + e + f + g
if (state in results):
prob[state] =␣
,→results[state]/num_shots

else:
prob[state] = 0.

angles = []
for c in chars:
for d in chars:
for e in chars:
for f in chars:
zero = "0000" + c + d + e + f
one = "1000" + c + d + e + f
zero_prob = prob[zero]/(prob[zero] +␣
,→prob[one])

angles.append(acos(sqrt(zero_prob)))

return angles

def run(angles):

qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)

qc= qk.QuantumCircuit(qr,cr)

# angles to rotate by
red = (pi/2) * (1/r_num)
green = (pi/2) * (1/g_num)
blue = (pi/2) * (1/b_num)
# shift by
s = 8 * 2

#Creating the Hadamard State


qc.h(qr[0])
qc.h(qr[1])

22
# Circuit for I(theta) starts here
qc.x(qr[0])
qc.x(qr[1])

#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[1],qr[2])

#pi/12=0.2617
qc.x(qr[0])

qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[1],qr[2])

#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])

qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[1],qr[2])

#pi/16=0.1963
qc.x(qr[0])

qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[1],qr[2])

qc.u3(s * red,0,0,qr[2])

qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)

23
result_sim = job_sim.result()

# In[42]:
counts = result_sim.get_counts(qc)

new_angles = probs(counts)

return new_angles

def run_4(angles):

# can just pass in the same angles as I did for 2x2. No need to double␣
them.
,→

for i in range(len(angles)):
angles[i] = 2 * angles[i]

# we are including 3 ancilla qubits


qr =qk.QuantumRegister(8)
cr = qk.ClassicalRegister(8)

qc= qk.QuantumCircuit(qr,cr)

#Creating the Hadamard State


qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])

# angle to manipulate the colors by

for i in range(16):

qc.x(qr[0])

if (i % 4 == 2):
qc.x(qr[1])

if (i == 0 or i == 8):
qc.x(qr[1])
qc.x(qr[2])
qc.x(qr[3])

if (i == 4 or i == 12):
qc.x(qr[1])
qc.x(qr[2])

qc.ccx(qr[0], qr[1], qr[4])

24
qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[3], qr[5], qr[6])

qc.cu3(angles[i],0,0,qr[6],qr[7])

qc.ccx(qr[3], qr[5], qr[6])


qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[0], qr[1], qr[4])

"""
################
# pixel shifting

#C3not
qc.ccx(qr[0], qr[1], qr[4])
qc.ccx(qr[2], qr[4], qr[5])

qc.cx(qr[5], qr[3])

qc.ccx(qr[2], qr[4], qr[5])


qc.ccx(qr[0], qr[1], qr[4])

#C2not
qc.ccx(qr[0], qr[1], qr[2])

#CNOT
qc.cx(qr[0], qr[1])

#NOT
qc.x(qr[0])

################
"""

qc.barrier(qr)
qc.measure(qr,cr)

# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()

# In[42]:
counts = result_sim.get_counts(qc)

#print(counts)

25
new_angles = probs4(counts)

return new_angles

"""
def test():

for i in range(16):

angles = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
angles[i] = pi/2

run_4(angles)
#print("==============\n", i, "\n==============")

break
"""

def get_xs():

chars = ["0","1"]
vals = []

for i in chars:
for j in chars:
for k in chars:
for l in chars:
vals.append(i + j + k + l)

total = []
for i in range(16):

x_vals = []
word = vals[i]
for j in range(4):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')

total.append(x_vals)

for k in range(16):
for q in range(4):

26
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→

else:
new_val.
append('1')
,→

vals[k] = new_val
else:
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→

else:
new_val.
append('0')
,→

vals[k] = new_val

print("================ ", i, " =================")


print(vals)

print(total)

[ ]: from PIL import Image


import numpy as np
from math import pi, floor

r_num = 16
g_num = r_num ** 2
b_num = r_num ** 3

"""
img = Image.new('RGB', (60, 30), color = 'red')
img.save('pil_red.png')
"""
# Create a NumPy array, which has four elements. The top-left should be pure␣
,→red, the top-right should be pure blue, the bottom-left should be pure green,␣

,→and the bottom-right should be yellow

def double_size(im):

rows = len(im)

27
cols = len(im[0])

#half_r = rows/2
#half_c = cols/2

new_im = np.zeros(((rows * 2, cols * 2, 3)))

r = im[0]
first = r[0]
second = r[int(cols/2)]

for i in range(rows):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]

r = im[int(rows/2)]
first = r[0]
second = r[int(cols/2)]

for i in range(rows, rows * 2):


for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]

return new_im
"""
[[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]
[[5, 5, 250], [250, 250, 5], [250, 5, 5], [5, 250, 5]]
[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]
[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]]
"""
def double_size4(im):

rows = len(im)
cols = len(im[0])

new_im = np.zeros(((rows * 2, cols * 2, 3)))

r = im[0]
first = r[0]

28
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]

for i in range(int(rows/2)):
for j in range(int(cols/2)):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]

r = im[int(rows/4)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]

for i in range(int(rows/2), rows):


for j in range(int(cols/2)):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]

r = im[int(rows/2)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]

for i in range(rows, int(rows * (3/2))):


for j in range(int(cols/2)):

29
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]

r = im[int(3 * rows/4)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]

for i in range(int(rows * (3/2)), rows * 2):


for j in range(int(cols/2)):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]

return new_im

# given an rgb image as a regular python list, converts it into a numpy array␣
,→image

def make_image(rgbs):

rows = len(rgbs)
cols = len(rgbs[0])

new_im = np.zeros(((rows, cols, 3)))

# convert to numpy array and scale the image back up


for i in range(rows):
for j in range(cols):
for k in range(3):

30
new_im[i][j][k] = rgbs[i][j][k]

new_im = scale_up(new_im)

return new_im

def show_image(pixels, name):

# Create a PIL image from the NumPy array


image = Image.fromarray(pixels.astype('uint8'), 'RGB')

image_name = 'images/' + name + '.png'

# Save the image


image.save(image_name)
image.show()

def scale_up(image):

rows = len(image)
cols = len(image[0])
scale = 256/r_num
new_im = np.zeros(((rows, cols, 3)))

for i in range(rows):
for j in range(rows):
for k in range(3):
new_im[i][j][k] = image[i][j][k] * scale

return new_im

# since we're having to use a scaled down version (only 64 or 16 color values),␣
,→need to scale down image

def scale_down(image):

rows = len(image)
cols = len(image[0])
scale = 256/r_num
new_im = np.zeros(((rows, cols, 3)))

for i in range(rows):
for j in range(rows):
for k in range(3):
new_im[i][j][k] = floor(image[i][j][k] / scale)

return new_im

31
def get_image():

pixels = np.array([[[17, 17, 17], [240, 17, 17]], [[17, 240, 17], [17,␣
,→17, 240]]])

scaled = scale_down(pixels)

"""
# Windows looking symbol
pixels = np.array([[[250, 5, 5], [5, 250, 5]], [[5, 5, 250], [250, 250,␣
5]]])
,→

scaled = scale_down(pixels)
"""

return scaled

def get_image4():

pixels = np.array([[[239, 239, 239], [239, 239, 239], [239, 239, 239],␣
,→[239, 239, 239]],
[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]],

[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]],

[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]]])

"""
# 4test w16 and changed to less extreme vals
pixels = np.array([[[239, 16, 16], [239, 100, 100], [239, 175, 175],␣
,→[230, 230, 230]],

[[175, 16, 16], [16, 16, 100], [16, 16, 239], [175, 239, 175]],
[[100, 16, 16], [16, 16, 150], [16, 16, 200], [100, 239, 100]],
[[16, 16, 16], [16, 100, 16], [16, 175, 16], [16, 239, 16]]])
"""
"""
# 4test
pixels = np.array([[[250, 5, 5], [250, 100, 100], [250, 175, 175], [235,␣
,→235, 235]],

[[175, 5, 5], [5, 5, 100], [5, 5, 250], [175, 250, 175]],


[[100, 5, 5], [5, 5, 150], [5, 5, 200], [100, 250, 100]],
[[5, 5, 5], [5, 100, 5], [5, 175, 5], [5, 250, 5]]])
"""

"""
pixels = np.array([[[250, 5, 5], [200, 5, 5], [150, 5, 5], [100, 5, 5]],
[[200, 5, 5], [5, 5, 100], [5, 5, 250], [150, 5, 5]],

32
[[150, 5, 5], [5, 5, 150], [5, 5, 200], [200, 5, 5]],
[[100, 5, 5], [150, 5, 5], [200, 5, 5], [250, 5, 5]]])
"""

scaled = scale_down(pixels)

return scaled

def rgb_to_theta(rgb):

r, g, b = rgb
theta = (pi/2) * ((r/r_num) + (g/g_num) + (b/b_num))
#print("Theta is ", theta)
return theta

def theta_to_rgb(theta):

r = floor(theta/(pi/(r_num * 2)))
theta = theta - r*(pi/(r_num * 2))

g = floor(theta/(pi/(g_num * 2)))
theta = theta - g*(pi/(g_num * 2))

b = floor(theta/(pi/(b_num * 2)))

return [r,g,b]

def test_it():

list = []
for i in range(2):
for j in range(2):
for k in range(2):
list.append([i, j, k])

i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)

def test_image():

im = get_image()

33
im = scale_up(im)

for i in range(7):
im = double_size(im)

show_image(im, "aman_test")

[ ]: import i_theta
import image_testing
from math import pi

if __name__ == '__main__':

image = image_testing.get_image()

print("The original image was: ", image)


size = len(image)

angles = []
# convert all rgb pixel values into angles in [0, pi/2]
for i in range(size):
for j in range(size):
angles.append((image_testing.rgb_to_theta(image[i][j])))

print("The angles for the original image: ", angles)

new_angles = i_theta.run(angles)

print("The returned angles are: ", new_angles)

im = []
i = 0
# converting all the recovered angles, back into rgb values
for ang in new_angles:

rgb = image_testing.theta_to_rgb(ang)
print(rgb)
if (i % 2 == 0):
row = []

row.append(rgb)

if (i % 2 != 0):
im.append(row)

i += 1

34
new_image = image_testing.make_image(im)

for i in range(7):
new_image = image_testing.double_size(new_image)

image_testing.show_image(new_image, "ijijiijjij")

[ ]: import i_theta
import image_testing
from math import pi

if __name__ == '__main__':

image = image_testing.get_image4()

print("The original image was: ", image)


size = len(image)

angles = []
# convert all rgb pixel values into angles in [0, pi/2]
for i in range(size):
for j in range(size):
angles.append((image_testing.rgb_to_theta(image[i][j])))

print("The angles for the original image: ", angles)

new_angles = i_theta.run_4(angles)

print("The returned angles are: ", new_angles)

im = []
i = 0
# converting all the recovered angles, back into rgb values
for ang in new_angles:

rgb = image_testing.theta_to_rgb(ang)
print(rgb)
if (i % 4 == 0):
row = []

row.append(rgb)

if (i % 4 == 3):
im.append(row)

35
i += 1

new_image = image_testing.make_image(im)

for i in range(6):
new_image = image_testing.double_size4(new_image)

image_testing.show_image(new_image, "Four_w16_100-000-000_SHIFTED")

[ ]: # Import the Qiskit SDK


from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer

num_measurements = 10000

def run():

# Create a Quantum Register with 2 qubits.


q = QuantumRegister(2)
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)

# Add a H gate on qubit 0, putting this qubit in superposition.


qc.h(q[0])
qc.h(q[1])

qc.measure(q, c)

#print("Aer backends: ", Aer.backends())

backend_sim = Aer.get_backend('qasm_simulator')

job_sim = execute(qc, backend_sim, shots=num_measurements)


result_sim = job_sim.result()

print(result_sim.get_counts(qc))

36
[1]: import numpy as np
import matplotlib.pyplot as plt

def apply_quantum_inspired_blur(image, blur_factor):


rows, cols = image.shape
blurred_image = np.zeros_like(image, dtype=float)

for i in range(rows):
for j in range(cols):
# Quantum-inspired blur: Each pixel is replaced by the average of␣
,→its neighbors

blurred_image[i, j] = np.mean(image[max(0, i-1):min(rows, i+2),␣


,→max(0, j-1):min(cols, j+2)])

# Apply blur factor


blurred_image = blurred_image * blur_factor

return blurred_image

# Generate a simple grayscale image


image_size = 10
image = np.random.rand(image_size, image_size)

# Display the original image


plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')

# Apply quantum-inspired blur


blur_factor = 0.8
blurred_image = apply_quantum_inspired_blur(image, blur_factor)

# Display the blurred image


plt.subplot(1, 2, 2)
plt.title('Blurred Image')
plt.imshow(blurred_image, cmap='gray')

plt.show()

1
[2]: import numpy as np
import matplotlib.pyplot as plt

# Generate a sample grayscale image (8x8 pixels)


image = np.random.rand(8, 8)

# Apply a simple Gaussian blur filter


def gaussian_blur(image):
kernel = np.array([[1, 2, 1],
[2, 4, 2],
[1, 2, 1]])
kernel = kernel / np.sum(kernel)
blurred_image = np.zeros_like(image)
for i in range(1, image.shape[0]-1):
for j in range(1, image.shape[1]-1):
blurred_image[i, j] = np.sum(image[i-1:i+2, j-1:j+2] * kernel)
return blurred_image

# Apply Gaussian blur


blurred_image = gaussian_blur(image)

# Display original and blurred images


plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.axis('off')

2
plt.subplot(1, 2, 2)
plt.title('Blurred Image')
plt.imshow(blurred_image, cmap='gray')
plt.axis('off')

plt.show()

[ ]:

3
[1]: import numpy as np
import matplotlib.pyplot as plt

def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values

# Display the colored boxes


fig, ax = plt.subplots()
ax.imshow(colors, interpolation='nearest')

# Add grid lines


ax.set_xticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.grid(which="minor", color="black", linestyle='-', linewidth=2)

# Hide tick labels


ax.set_xticks([])
ax.set_yticks([])

plt.show()

# Call the function to display colored boxes


display_colored_boxes()

1
[2]: import numpy as np
import matplotlib.pyplot as plt

def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values

# Display the colored boxes


fig, ax = plt.subplots()
ax.imshow(colors, interpolation='nearest')

# Add grid lines


ax.set_xticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.grid(which="minor", color="black", linestyle='-', linewidth=2)

# Hide tick labels


ax.set_xticks([])
ax.set_yticks([])

plt.show()

# Call the function to display colored boxes


display_colored_boxes()

2
[3]: import numpy as np
import matplotlib.pyplot as plt

def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values

# Display the colored boxes


fig, ax = plt.subplots()
ax.imshow(colors, interpolation='nearest')

# Add grid lines


ax.set_xticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.grid(which="minor", color="black", linestyle='-', linewidth=2)

# Hide tick labels


ax.set_xticks([])
ax.set_yticks([])

plt.show()

# Call the function to display colored boxes

3
display_colored_boxes()

[4]: import numpy as np


import matplotlib.pyplot as plt

def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values

# Display the colored boxes


fig, ax = plt.subplots()
ax.imshow(colors, interpolation='nearest')

# Add grid lines


ax.set_xticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 3.5, 1), minor=True)
ax.grid(which="minor", color="black", linestyle='-', linewidth=2)

# Hide tick labels


ax.set_xticks([])
ax.set_yticks([])

plt.show()

4
# Call the function to display colored boxes
display_colored_boxes()

[5]: import matplotlib.pyplot as plt

# Create a 2x2 grid of subplots


fig, ax = plt.subplots(2, 2, figsize=(6, 6))

# Define colors for each box


colors = ['red', 'green', 'blue', 'purple']

# Plot each box with a different color


for i in range(2):
for j in range(2):
ax[i, j].add_patch(plt.Rectangle((0, 0), 1, 1, color=colors[i * 2 + j]))
ax[i, j].set_xlim(0, 1)
ax[i, j].set_ylim(0, 1)
ax[i, j].axis('off') # Turn off axis labels and ticks

# Adjust layout
plt.tight_layout()

5
# Show the plot
plt.show()

[ ]:

6
[1]: import numpy as np
import matplotlib.pyplot as plt

def create_colored_image():
# Create a 4x4 grid with colors: red, green, blue, yellow
colors = {
'red': (1, 0, 0),
'green': (0, 1, 0),
'blue': (0, 0, 1),
'yellow': (1, 1, 0)
}

image_size = 4
color_image = np.zeros((image_size, image_size, 3))

for i in range(image_size):
for j in range(image_size):
if i < image_size // 2 and j < image_size // 2:
color_image[i, j] = colors['red']
elif i < image_size // 2:
color_image[i, j] = colors['green']
elif j < image_size // 2:
color_image[i, j] = colors['blue']
else:
color_image[i, j] = colors['yellow']

return color_image

def display_colored_image(image):
# Display the colored image
plt.imshow(image)
plt.axis('off')
plt.show()

# Create the colored image


colored_image = create_colored_image()

# Display the colored image


display_colored_image(colored_image)

1
[2]: import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter

def create_colored_image():
colors = {
'red': (1, 0, 0),
'green': (0, 1, 0),
'blue': (0, 0, 1),
'yellow': (1, 1, 0)
}

image_size = 4
color_image = np.zeros((image_size, image_size, 3))

for i in range(image_size):
for j in range(image_size):
if i < image_size // 2 and j < image_size // 2:
color_image[i, j] = colors['red']
elif i < image_size // 2:
color_image[i, j] = colors['green']
elif j < image_size // 2:
color_image[i, j] = colors['blue']

2
else:
color_image[i, j] = colors['yellow']

return color_image

def display_image(image, title):


plt.imshow(image)
plt.title(title)
plt.axis('off')
plt.show()

def apply_classical_blur(image, sigma=1.0):


# Apply Gaussian blur using scipy's gaussian_filter
blurred_image = gaussian_filter(image, sigma=(sigma, sigma, 0),␣
,→mode='constant')

return blurred_image

# Create the original colored image


original_colored_image = create_colored_image()

# Display the original colored image


display_image(original_colored_image, 'Original Colored Image')

# Apply classical blur to the original image


sigma_value = 1.5
blurred_colored_image = apply_classical_blur(original_colored_image,␣
,→sigma=sigma_value)

# Display the blurred colored image


display_image(blurred_colored_image, f'Blurred Colored Image␣
,→(Sigma={sigma_value})')

3
4
[ ]:

5
[1]: import numpy as np

# Create an 8x8 NumPy array for the binary image


binary_image = np.array([
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0]
], dtype=np.uint8)

# Display the binary image


print(binary_image)

[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]

[2]: import numpy as np

# Create an 8x8 NumPy array for a color image


color_image = np.zeros((8, 8, 3), dtype=np.uint8)

# Set some example color values (R, G, B) for each pixel


color_image[:, :, 0] = 255 # Set red channel to maximum intensity
color_image[:, :, 1] = 128 # Set green channel to a medium intensity
color_image[:, :, 2] = 0 # Set blue channel to minimum intensity

# Display the color image


print(color_image)

[[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

1
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]

2
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]

[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]]

[ ]:

3
[1]: import numpy as np
import matplotlib.pyplot as plt

# Create a random 8x8 color box


color_box = np.random.randint(0, 256, size=(8, 8, 3), dtype=np.uint8)

# Display the original color box


plt.imshow(color_box)
plt.title('Original Color Box')
plt.show()

# Calculate and plot histograms for each color channel


for i, color in enumerate(['Red', 'Green', 'Blue']):
plt.hist(color_box[:, :, i].ravel(), bins=256, color=color.lower(), alpha=0.
,→5, label=color)

plt.title('Histograms for each Color Channel')


plt.xlabel('Intensity')
plt.ylabel('Frequency')
plt.legend()
plt.show()

# Rotate the color box (90 degrees counterclockwise)


rotated_color_box = np.rot90(color_box, k=1, axes=(0, 1))

# Display the rotated color box


plt.imshow(rotated_color_box)
plt.title('Rotated Color Box')
plt.show()

1
2
3
[ ]:

4
[1]: from qiskit import *
from qiskit import IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import skimage.color
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('bmh')
import math

[2]: from PIL import Image, ImageOps


style.use('default')

image_size = 256 # Original image-width


image_crop_size = 32 # Width of each part of image for processing

# Load the image from filesystem


image_ip = Image.open("data.png")
#pixels = array(image_ip)
image_raw = np.array(Image.open('data.png'))
print('Raw Image info:', image_raw.shape)
print('Raw Image datatype:', image_raw.dtype)
#print(pixels)

# Convert the RBG component of the image to B&W image, as a numpy (uint8) array
if len(image_raw.shape) == 2:
image_raw = skimage.color.gray2rgb(image_raw)
print(image_raw.shape)
image = []
for i in range(image_size):
image.append([])
for j in range(image_size):
image[i].append(image_raw[i][j][0] / 255)

image = np.array(image)
print('Image shape (numpy array):', image.shape)

# Display the image


plt.title('Big Image')
plt.xticks(range(0, image.shape[0]+1, 32))

1
plt.yticks(range(0, image.shape[1]+1, 32))
plt.imshow(image, extent=[0, image.shape[0], image.shape[1], 0], cmap='viridis')
plt.show()

Raw Image info: (256, 256, 4)


Raw Image datatype: uint8
(256, 256, 4)
Image shape (numpy array): (256, 256)

[3]: # Convert the raw pixel values to probability amplitudes


def amplitude_encode(img_data):

# Calculate the RMS value


rms = np.sqrt(np.sum(np.sum(img_data**2, axis=1)))

# Create normalized image


image_norm = []
for arr in img_data:
for ele in arr:
image_norm.append(ele / rms)

2
# Return the normalized image as a numpy array
return np.array(image_norm)

[4]: # Initialize some global variable for number of qubits


data_qb = math.ceil(math.log2(image_crop_size**2))
anc_qb = 1
total_qb = data_qb + anc_qb
print('total qbits ' ,total_qb)
# Initialize the amplitude permutation unitary
D2n_1 = np.roll(np.identity(2**total_qb), 1, axis=1)

total qbits 11

[5]: (imageWidth, imageHeight)=image_ip.size

gridx=32
gridy=32
image_splits = []
image_ip_pro = np.array(image_ip)
for h in range(0,imageHeight,gridy):
for w in range(0,imageWidth,gridx):
# bbox=(x*gridx, y*gridy, x*gridx+gridx, y*gridy+gridy)
# slice_bit=image_ip.crop(bbox)
# slice_bit = np.array(slice_bit)
slice_bit = image_ip_pro[h:h+gridy, w:w+gridx,0]
slice_bit = slice_bit / 255
image_splits.append(slice_bit)

# plt.imshow(image_splits[0])
# plt.show()
# plt.imshow(image_splits[1])
# plt.show()

[ ]: import time

def runOnSimulator(back, circuit, qc_h, qc_v):


results = execute(circuit, backend=back).result()
sv_h = results.get_statevector(qc_h)
sv_v = results.get_statevector(qc_v)
return sv_h,sv_v

threshold = lambda amp: (amp > 1e-15 or amp < -1e-15)


back = Aer.get_backend('statevector_simulator')
qc_h = QuantumCircuit(total_qb)
qc_v = QuantumCircuit(total_qb)

edges = []
tot_time = time.time()

3
for i in range(len(image_splits)):
start_time = time.time()

img = image_splits[i]
print(img.shape)
image_norm_h = amplitude_encode(img)
image_norm_v = amplitude_encode(img.T)
print('encoding', time.time() - start_time)
print(image_norm_h.shape)
# horizontal
qc_h.initialize(image_norm_h, range(1, total_qb))
qc_h.h(0)
qc_h.unitary(D2n_1, range(total_qb))
qc_h.h(0)
print('horizontal', time.time() - start_time)
# display(qc_h.draw('mpl', fold=-1))

# vertical
qc_v.initialize(image_norm_v, range(1, total_qb))
qc_v.h(0)
qc_v.unitary(D2n_1, range(total_qb))
qc_v.h(0)
print('vertical', time.time() - start_time)
# display(qc_v.draw('mpl', fold=-1))
# forming the circuit
circ_list = [qc_h, qc_v]

#running the ciruit


sv_h, sv_v = runOnSimulator(back, circ_list, qc_h, qc_v)
print('running', time.time() - start_time)
edge_scan_h = np.abs(np.array([1 if threshold(sv_h[2*i+1].real) else 0 for i␣
,→in range(2**data_qb)])).reshape(gridy, gridx)

edge_scan_v = np.abs(np.array([1 if threshold(sv_v[2*i+1].real) else 0 for i␣


,→in range(2**data_qb)])).reshape(gridy, gridx).T

print('extracting', time.time() - start_time)


edge_scan_sim = edge_scan_h | edge_scan_v
plt.imshow(edge_scan_sim)
plt.show()
edges.append(edge_scan_sim)
print(time.time() - start_time)
# plot_image(edge_scan_sim, 'Edge Detected image')
print('total time',time.time() - tot_time)

(32, 32)
encoding 0.0007760524749755859
(1024,)
horizontal 0.7311007976531982

4
vertical 1.435943603515625
running 144.20826506614685
extracting 144.20990562438965

144.34677839279175
(32, 32)
encoding 0.0006000995635986328
(1024,)
horizontal 0.5885050296783447
vertical 1.1858634948730469
running 292.49501490592957
extracting 292.49710845947266

5
292.62941813468933
(32, 32)
encoding 0.000667572021484375
(1024,)
horizontal 0.8226900100708008
vertical 1.6138217449188232
running 441.564177274704
extracting 441.56613755226135

6
441.69841623306274
(32, 32)
encoding 0.0006420612335205078
(1024,)
horizontal 0.5834693908691406
vertical 1.412827730178833
running 582.2895851135254
extracting 582.2910220623016

7
582.426659822464
(32, 32)
encoding 0.0005407333374023438
(1024,)
horizontal 0.7885682582855225
vertical 1.658304214477539
running 737.131618976593
extracting 737.1332285404205

8
737.4328744411469
(32, 32)
encoding 0.0007634162902832031
(1024,)
horizontal 1.0512843132019043
vertical 1.8754756450653076
running 888.8279981613159
extracting 888.8295588493347

9
889.009110212326
(32, 32)
encoding 0.0007188320159912109
(1024,)
horizontal 0.7772834300994873
vertical 1.5633196830749512

[ ]:

10
[1]: import numpy as np

def qft(matrix):
# Apply Quantum Fourier Transform on a 2D NumPy matrix

rows, cols = matrix.shape


result = np.zeros((rows, cols), dtype=np.complex128)

for u in range(rows):
for v in range(cols):
factor = np.exp(2j * np.pi * (u * np.arange(rows) / rows + v * np.
,→arange(cols) / cols))

result[u, v] = np.sum(matrix * factor)

return result / np.sqrt(rows * cols)

# Example usage
image = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=np.complex128)

qft_result = qft(image)

print("Original Image:\n", image)


print("\nQuantum Fourier Transform Result:\n", qft_result)

Original Image:
[[1.+0.j 2.+0.j 3.+0.j]
[4.+0.j 5.+0.j 6.+0.j]
[7.+0.j 8.+0.j 9.+0.j]]

Quantum Fourier Transform Result:


[[15. +0.00000000e+00j -1.5-8.66025404e-01j -1.5+8.66025404e-01j]
[-1.5-8.66025404e-01j -1.5+8.66025404e-01j 15. -4.16379912e-15j]
[-1.5+8.66025404e-01j 15. -4.16379912e-15j -1.5-8.66025404e-01j]]

[2]: import numpy as np


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def qft(matrix):
rows, cols = matrix.shape
result = np.zeros((rows, cols), dtype=np.complex128)

for u in range(rows):
for v in range(cols):

1
factor = np.exp(2j * np.pi * (u * np.arange(rows) / rows + v * np.
arange(cols) / cols))
,→

result[u, v] = np.sum(matrix * factor)

return result / np.sqrt(rows * cols)

# Create a sample quantum image


image_size = 8
quantum_image = np.random.random((image_size, image_size)) + 1j * np.random.
,→random((image_size, image_size))

# Apply QFT to the quantum image


qft_result = qft(quantum_image)

# Create 3D surface plot


fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')

u, v = np.meshgrid(np.arange(image_size), np.arange(image_size))
ax.plot_surface(u, v, np.abs(qft_result), cmap='viridis')

ax.set_xlabel('U-axis')
ax.set_ylabel('V-axis')
ax.set_zlabel('Magnitude')

plt.title('Quantum Fourier Transform Result')


plt.show()

2
[ ]:

3
Designing a quantum image classifier using Data Re-uploading Quantum Convolution and a
Data Re-uploading Classifier Scheme involves combining concepts from quantum computing
and machine learning. This is a complex task, and the field is still evolving. Below is a
simplified outline of the steps you might consider when designing such a quantum image
classifier:

1. Quantum Image Representation:


• Represent the classical image data in a quantum form. This might involve
encoding pixel values as quantum states.
2. Quantum Convolution:
• Design a quantum convolutional layer. Classical convolutional layers are
used in classical image classifiers for feature extraction. Quantum
convolutional layers would need to operate on quantum states.
3. Data Re-uploading Quantum Convolution:
• Implement the concept of data re-uploading in the quantum convolutional
layer. This involves introducing additional parameters that can be optimized
during training. These parameters can be adjusted to enhance the
expressiveness of the quantum convolutional layer.
4. Quantum Classifier:
• Design a quantum classifier that takes the features extracted by the quantum
convolutional layer and makes a decision. This could be a quantum circuit
that applies a series of operations to the quantum states.
5. Data Re-uploading Classifier Scheme:
• Apply data re-uploading to the quantum classifier. Introduce additional
parameters that can be optimized to improve the classification accuracy.
6. Quantum Training Algorithm:
• Develop a training algorithm that leverages quantum computing capabilities.
This might involve using quantum gradient descent or other quantum
optimization techniques.
7. Quantum Circuit Implementation:
• Implement the designed quantum circuits using a quantum programming
framework like Qiskit, Cirq, or any other suitable framework for your
quantum computer.
8. Hybrid Classical-Quantum Approach:
• Consider a hybrid approach where classical machine learning techniques are
used in conjunction with quantum components. This is often necessary
because quantum computers currently have limitations in terms of the number
of qubits and coherence times.
9. Quantum Error Correction:
• Implement quantum error correction codes to mitigate the impact of noise and
errors in quantum computations.
10. Evaluate and Fine-tune:
• Evaluate the performance of your quantum image classifier on test data. Fine-
tune the parameters and architecture to improve accuracy.
Remember, this is a highly complex task and might require a deep understanding of both
quantum computing and machine learning. Additionally, the practical implementation may be
constrained by the current limitations of existing quantum hardware.
An animation showing how the quantum states evolve on the Bloch sphere during training.
Every point represents a data point, with blue color shows data points of number 0 and red
color shows data points of number 1 in the MNIST dataset. At the start, all the data points
got mapped randomly on to a single location in the Bloch sphere, as the circuit parameters
are randomly generated. But after several training iteration, we can see that the circuit maps
the blue points toward the |0⟩ state and the red points toward the |1⟩ state, indicating that the
circuit is now able to differentiate different numbers in the dataset.

You might also like