Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added demo for #131 #148

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions demos/brqi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@

# BRQI Demo

This demo showcases the Bitplane Representation of Quantum Images (BRQI) using the piQture library. It demonstrates how to load an image, convert it to a quantum circuit using BRQI encoding, and visualize the results.

## Prerequisites

- Python 3.7+
- piQture library
- Qiskit
- NumPy
- Pillow (PIL)
- Matplotlib

## Installation

1. Install the required libraries:

```
pip install piqture qiskit qiskit-aer numpy pillow matplotlib
```

2. Clone the piQture repository or ensure you have the BRQI module available.

## Usage

1. Place your input image in a known location.

2. Update the `image_path` variable in the `main()` function:


```
def main():
# Path to your input image
image_path = '/Users/dylanmoraes/Downloads/image-1.png'
```


3. Run the script:

```
python brqi_demo.py
```

## How it works

The demo follows these steps:

1. **Load and preprocess the image**:
- Opens the image file
- Converts it to grayscale
- Resizes it to a small dimension (default 4x4)
- Normalizes pixel values to the range [0, 255]

2. **Create BRQI circuit**:
- Initializes a BRQI object with the image dimensions and pixel values
- Generates the quantum circuit representation of the image

3. **Visualize results**:
- Displays the original image
- Simulates the quantum circuit using Qiskit's QASM simulator
- Plots a histogram of the measurement results

## Customization

- To change the target size of the image, modify the `target_size` parameter in the `load_and_preprocess_image()` function call:


```67:67:demos/brqi_demo.py
img_array = load_and_preprocess_image(image_path)
```


- To adjust the number of shots in the quantum simulation, change the `shots` parameter in the `backend.run()` function:


```
job = backend.run(transpiled_circuit, shots=1000)
```


## Understanding the Output

The script will display two plots:
1. The original grayscale image
2. A histogram of the measurement results from the quantum circuit simulation

The histogram represents the probability distribution of different quantum states, which encodes the information from the original image in the BRQI format.

## Troubleshooting

If you encounter any issues:
- Ensure all required libraries are installed correctly
- Check that the image path is correct and the file exists
- Verify that the piQture library and BRQI module are properly imported

For more information on the BRQI encoding method and the piQture library, refer to the main piQture documentation.
119 changes: 119 additions & 0 deletions demos/brqi_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# pylint: disable=R0801
"""Demo script for BRQI (Binary Representation of Quantum Images) encoding.

This script demonstrates how to load an image, convert it to BRQI representation,
and visualize the results using quantum circuit simulation.
"""

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from qiskit import transpile
from qiskit.visualization import plot_histogram
from qiskit_aer import Aer

from piqture.embeddings.image_embeddings.brqi import BRQI


def load_and_preprocess_image(image_path, target_size=(4, 4)):
"""Load and preprocess an image for BRQI encoding.

Args:
image_path (str): Path to the input image file
target_size (tuple): Desired dimensions for the resized image (default: (4, 4))

Returns:
numpy.ndarray: Preprocessed image array with normalized pixel values
"""
# Load the image
img = Image.open(image_path)

# Convert to grayscale
img = img.convert("L")

# Resize the image
img = img.resize(target_size)

# Convert to numpy array
img_array = np.array(img)

# Normalize pixel values to range [0, 255]
img_array = (img_array / img_array.max() * 255).astype(int)

return img_array


def create_brqi_circuit(img_array):
"""Create a quantum circuit using BRQI encoding for the input image.

Args:
img_array (numpy.ndarray): Input image array with pixel values

Returns:
QuantumCircuit: BRQI encoded quantum circuit
"""
img_dims = img_array.shape
pixel_vals = [img_array.flatten().tolist()]

# Create BRQI object
brqi_object = BRQI(img_dims, pixel_vals)

# Generate BRQI circuit
brqi_circuit = brqi_object.brqi()

return brqi_circuit


def visualize_results(original_image, brqi_circuit):
"""Visualize the original image and quantum circuit simulation results.

Args:
original_image (numpy.ndarray): The original input image array
brqi_circuit (QuantumCircuit): The BRQI encoded quantum circuit

Returns:
None: Displays plots of the original image and measurement results
"""
# Display original image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(original_image, cmap="gray")
plt.title("Original Image")

# Simulate the quantum circuit
backend = Aer.get_backend("qasm_simulator")
transpiled_circuit = transpile(brqi_circuit, backend)
job = backend.run(transpiled_circuit, shots=1000)
result = job.result()
counts = result.get_counts()

# Plot the histogram of measurement results
plt.subplot(1, 2, 2)
plot_histogram(counts)
plt.title("BRQI Measurement Results")

plt.tight_layout()
plt.show()


def main():
"""Main function to demonstrate BRQI encoding on an image.

This function serves as the entry point for the demo script.
It loads an image, creates a BRQI circuit, and visualizes the results.
"""
# Path to your input image
image_path = "/path/to/image.jpg"

# Load and preprocess the image
img_array = load_and_preprocess_image(image_path)

# Create BRQI circuit
brqi_circuit = create_brqi_circuit(img_array)

# Visualize results
visualize_results(img_array, brqi_circuit)


if __name__ == "__main__":
main()
Loading