Untitled
unknown
python
3 years ago
3.0 kB
16
Indexable
import numpy as np
import cv2
from PIL import Image
from qutip import Qobj, basis, tensor, qeye, sigmax, sigmay, sigmaz
def adjacency_matrix_4_neighborhood(width, height):
dim = width * height
adj_matrix = np.zeros((dim, dim))
for y in range(height):
for x in range(width):
i = y * width + x
if x > 0:
adj_matrix[i, i - 1] = 1
if x < width - 1:
adj_matrix[i, i + 1] = 1
if y > 0:
adj_matrix[i, i - width] = 1
if y < height - 1:
adj_matrix[i, i + width] = 1
return adj_matrix
def dtqw_operator(dim, coin_operator):
U = tensor(coin_operator, qeye(dim))
return U
def dtqw_step(state, U):
return U * state
def dtqw_segmentation(image, iterations, adj_matrix):
print("input_image dtype:", input_image.dtype)
print("input_image shape:", input_image.shape)
pil_image = Image.fromarray(image)
pil_gray_image = pil_image.convert('L')
gray_image = np.array(pil_gray_image)
if gray_image is None:
raise ValueError("Failed to convert the image to grayscale.")
print("Gray image shape:", gray_image.shape)
dim = gray_image.shape[0] * gray_image.shape[1]
coin_operator = 1 / np.sqrt(2) * (sigmax() + sigmay() + sigmaz())
U = dtqw_operator(dim, coin_operator)
initial_state = tensor(basis(2, 0), basis(dim, 0))
initial_state_array = np.array(initial_state.full()).reshape(U.shape[0], 1) # Convert to NumPy array and reshape
for _ in range(iterations):
initial_state_array = dtqw_step(initial_state_array, U)
probabilities = np.abs(initial_state_array) ** 2
print("Probabilities shape:", probabilities.shape)
# Resize probabilities array to match the size of gray image
resized_probabilities = cv2.resize(probabilities, (gray_image.shape[1], gray_image.shape[0]))
segmented_image = gray_image * resized_probabilities # Element-wise multiplication
print("Segmented image shape:", segmented_image.shape)
return segmented_image
# Load the input image
input_image = cv2.imread('input_image.jpg')
if input_image is None:
raise ValueError("Image not loaded. Check the file path and format.")
elif len(input_image.shape) < 3 or input_image.shape[2] < 3:
raise ValueError("The input image is not a color image.")
else:
print("Image loaded successfully")
# Generate the adjacency matrix for the image
height, width = input_image.shape[:2]
adj_matrix = adjacency_matrix_4_neighborhood(width, height)
# Apply DTQW segmentation
iterations = 100
segmented_image = dtqw_segmentation(input_image, iterations, adj_matrix)
# Normalize the segmented image to the range [0, 255]
segmented_image_normalized = cv2.normalize(segmented_image, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX,
dtype=cv2.CV_8U)
# Save the segmented image
cv2.imwrite('segmented_image.jpg', segmented_image_normalized)Editor is loading...