Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.9 kB
2
Indexable
Never
import numpy as np
import cv2
from qutip import Qobj, basis, tensor, qeye, sigmax, sigmay, sigmaz
import warnings

warnings.filterwarnings("ignore", category=UserWarning, module="qutip")


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)) * (tensor(basis(2, 0), qeye(dim)) * tensor(basis(2, 0).dag(), basis(dim, 0)) +
                                            tensor(basis(2, 1), qeye(dim)) * tensor(basis(2, 1).dag(), basis(dim, 1)))
    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)
    image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    gray_image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

    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))

    for _ in range(iterations):
        initial_state = dtqw_step(initial_state, U)

    probabilities = np.abs(initial_state.full()) ** 2
    print("Probabilities shape:", probabilities.shape)
    segmented_image = np.reshape(probabilities, gray_image.shape).real
    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
adj_matrix = adjacency_matrix_4_neighborhood(width, height)

# Apply DTQW segmentation
iterations = 1000
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)