Path: blob/main/notebooks/ch-applications/quantum-edge-detection.ipynb
3855 views
Quantum edge detection
An essential part of any image feature extraction procedure is Edge Detection. The process of edge detection is used extensively in modern classical image processing algorithms for extracting the structure of the objects/features depicted in an image. Quantum Image processing being an emerging field, is very intriguing and enables one to have exponential speedup (as mentioned in their paper by Ruan et al. [6]), in certain cases over classical image processing. Although, edge detection is fairly efficient in classical image processing, it becomes very slow for larger images due to the huge resolution of these images and the pixel-wise computation that is necessary for most of the classical edge detection algorithms.
On the other hand, the previous application shows how one can convert classical images to quantum images using the Quantum Image Representations (QImRs) like Flexible Representation of Quantum Images (FRQI) [1] and Novel Enhanced Quantum Representation (NEQR) [2] techniques. This section discusses about the Quantum Probability Image Encoding (QPIE) [3] representation and also talks about extending the usage of these QImRs to perform edge detection using the Quantum Hadamard Edge Detection (QHED) algorithm [3].
Quantum Probability Image Encoding (QPIE)
The QPIE representation uses the probability amplitudes of a quantum state to store the pixel values of a classical image. If we have -qubits, we have access to up to -states in superposition. In QPIE we take advantage of this fact to design an efficient and robust encoding scheme for Black-and-White (B&W) or RGB images and exponentially reduce the memory required to store the data. That means, for storing a 4-pixel image, we need just 2-qubits; for 8-pixel image we need 3-qubits, and so on. In general, the number of qubits for a -pixel image is calculated as:-
ParseError: KaTeX parse error: Undefined control sequence: \label at position 27: …\log_2N \rceil \̲l̲a̲b̲e̲l̲{eq:Num_qubits}…Classical image to QPIE state
Let us take a sample image with four pixels which is arranged in 2D as follows:-

Here, the vector (or in binary representation of sub-script indices) represents color intensities (in 8-bit B&W color) of different pixels represented as a 2D matrix to form a classical image. The image can be represented in terms of it's pixel intensities as follows:
ParseError: KaTeX parse error: \newcommand{\braket} attempting to redefine \braket; use \renewcommandTherefore, ParseError: KaTeX parse error: Undefined control sequence: \eqref at position 1: \̲e̲q̲r̲e̲f̲{eq:Classical_I… represent a 2-dimensional image made of pixels, where is the intensity of the pixel at the position in the 2D image starting the coordinate axes from the top-left corner of the image.
Now, we need to represent these pixel intensities as the probability amplitudes of a particular quantum state. To do this, the pixel intensities should be normalized so that the sum of the squares of all the probability amplitudes is 1. For every corresponding to respective , the normalization can be done as follows:-
ParseError: KaTeX parse error: Undefined control sequence: \label at position 44: …um I_{yx} ^2}} \̲l̲a̲b̲e̲l̲{eq:QPIE_normal…After aforementioned normalization, the quantum-image looks like,

Finally, assigning the normalized pixel color values of each pixel to the respective quantum state , we can write the image state as:-
ParseError: KaTeX parse error: Undefined control sequence: \label at position 78: …+ c_3 \ket{11} \̲l̲a̲b̲e̲l̲{eq:QPIE_Img} \…OR generalizing for -qubits, we have,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 53: …1} c_i \ket{i} \̲l̲a̲b̲e̲l̲{eq:QPIE_Img_su…Such a state can be very efficiently prepared just by using a few rotation and CNOT gates as can be seen in [7, 8]. A sample circuit for the above 4-pixel image example with B&W pixel values is as follows:-

Quantum Hadamard Edge Detection (QHED)
In general, classical edge detection algorithms rely mostly on the computation of image gradients i.e. identifying locations in the image for dark-to-light (or light-to-dark) intensity transitions. Hence, the worst case time complexity for most of them is . This means that each pixel needs to be processed individually to determine the gradients.
On the contrary, quantum edge detection algorithms like QSobel [4] provide exponential speedup compared to the existing classical edge detection algorithms. However, there are some steps involved in the algorithm that make it quite inefficient, for example the COPY operation and a quantum black box to calculate the gradients of all the pixels. For both the operations, there is no single efficient implementation that is known as of now and is a complex topic of research. Hence, the need for a much more efficient algorithm is fulfilled by the Quantum Hadamard Edge Detection (QHED) algorithm [3].
The case of the Hadamard gate
The Hadamard gate has the following operation on the state of qubit, ParseError: KaTeX parse error: \newcommand{\braket} attempting to redefine \braket; use \renewcommand
The QHED algorithm generalizes this action of -gate and uses it for edge detection of an image.
Let us assume we have an -pixel image. The pixels of the image can be numbered using binary bit-strings in the form of where .
For two neighboring pixels, the bit-strings can be written as and , i.e. only the least significant bit (LSB) is different for both of them. The corresponding pixel intensity values (normalized) can be written as and respectively. To simplify the notation, we will resort to the decimal representation of the bit-strings. Hence, the pixel values can be written as and in decimal representation.
Now, if we apply the -gate to the LSB of an arbitrary size quantum register, we can represent the resultant unitary like,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 341: … \end{bmatrix} \̲l̲a̲b̲e̲l̲{eq:had_on_lsb}…Applying this unitary to a quantum register containing pixel values encoded using the QPIE representation , as shown in , we have,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 288: … \end{bmatrix} \̲l̲a̲b̲e̲l̲{eq:interferenc…From the above resultant matrix ParseError: KaTeX parse error: Undefined control sequence: \eqref at position 1: \̲e̲q̲r̲e̲f̲{eq:interferenc…, it is clearly visible that we now have access to the gradient between the pixel intensities of neighboring pixels in the form of where, is even. Measuring the circuit conditioned on the LSB being in state , we can obtain the gradients through statistical analysis.
This process results in the detection of horizontal boundaries between the even-pixels-pairs ( & , & , and so on). For detecting horizontal boundaries between odd-pixel-pairs ( & , & , etc.), we can perform an amplitude permutation on the quantum register to convert the amplitude vector to , and then applying the -gate and measuring the quantum register conditioned on LSB being .
However, we can make it more resource-efficient by using an additional auxiliary qubit!
A Variation of QHED (with an auxiliary qubit)
As discussed in the previous sub-section, we still have a quantum register with -qubits for encoding the -pixel image. However, in this case, we add an extra auxiliary qubit to the register which we can utilize to extend the QHED algorithm and perform computation on both even- and odd-pixel-pairs simultaneously.
Like the last time, we initialize to the state . However, the -gate is now applied to the auxiliary qubit this time which is initialized to state .
This produces an -qubit redundant image state which can be represented as,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 210: … \end{bmatrix} \̲l̲a̲b̲e̲l̲{eq:hadamard_on…Now, since we get the redundant probability amplitudes obtained in the resultant state in ParseError: KaTeX parse error: Undefined control sequence: \eqref at position 1: \̲e̲q̲r̲e̲f̲{eq:hadamard_on…, we can define an amplitude permutation unitary as follows to transform the amplitudes into a structure which will make it easier to calculate the image gradients further ahead,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 307: … \end{bmatrix} \̲l̲a̲b̲e̲l̲{eq:amp_perm_un…The above unitary corresponds to a Decrement gate. Hence, we can efficeintly decompose this unitary into a set of single- and multi-controlled-X rotations on a register of multiple qubits as shown by Fijany and Williams in [9] and Gidney in [10].
Applying the above decrement gate unitary to the redundant image state, we can transform the state to the new redundant image state .
Now again if we apply the -gate to the auxiliary qubit, we obtain the gradients for both even- and odd-pixel-pairs at the same time like so,
ParseError: KaTeX parse error: Undefined control sequence: \label at position 357: … \end{bmatrix} \̲l̲a̲b̲e̲l̲{eq:had_after_p…Finally, measuring this state conditioned on the auxiliary qubit being in state , we will get the resultant horizontal gradient values for all possible pairs of adjacent qubits.
NOTE: The above process provides a horizontal scan of the entire image which has edges detected in only the horizontal direction. To obtain the vertical scan edge detected image, we take the traspose of the image matrix and follow the same process again to obtain a vertical scan. These horizontal and vertical scans are then superimposed on each other using some classical post-processing to create the full edge detected image.
Quantum Circuit
Let us take a sample image, flattened and represented as the vector: ,

The QHED quantum circuit for the above image can be generalized as:

NOTE: The measurements of data qubits (, , , and ) is dependent on the measurement outcome of auxiliary qubit () being in the state
Time and Space Complexity analysis of QHED
We briefly discussed about the time complexity of classical edge detection algorithms and realised that it is on the order of for the worst case of the algorithm and for some of the more improved classical edge detection techniques [11].
On the other hand, when one comes to the quantum edge detection techniques, the QSobel algorithm is much faster at ,and uses the FRQI image representation for encoding an -pixel image (, in a -qubit system) [4]. However, the FRQI image representation has a complex state preparation process ( circuit depth in the worst case) and requires more qubits ( -qubits) to store the image data [1], which is a limited resource in today's hardware. Moreover, QSobel also suffers from problems with efficient implementation of certain intermediate sub-routines (like COPY and black-box function for gradient calculation) within the algorithm [3].
The QHED algorithm which is used here, has more space-efficient image encoding scheme (QPIE) which uses amplitude encoding leading to an exponential decrease in the number of qubits used (just -qubits). However, the time complexity of state-preparation step for image encoding using QPIE is slightly higher at [12], than FRQI. Also, the most efficient implementation of the decrement gate has the circuit depth of . But, since QHED smartly utilizes the property of the Hadamard-gate, we are able to achieve a time complexity of for the edge detection procedure (without including state-preparation and amplitude permutation). This is much lower than the complexity required for the QSobel algorithm. Hence, the QHED algorithm gives us a superexponential speedup over classical algorithms and polynomial speedup over the QSobel algorithm.
NOTE: Another aspect that we would need to focus on for making this quantum algorithm work is the number of measurements that one needs to make to get considerable accuracy for the algorithm. Generally, for a -qubit circuit, one requires measurements to get good precision for the output probabilities. However, if the goal is just to discover some specific patterns in the image, we can perform measurement of a single local observable with the number of measurements just on the order of [3]. However, this limitation is not of the algorithm, but a characteristic of the inherent quantum nature of the system on which the algorithm is run, and hence the quantum and classical edge detection algorithms are not directly comparable only on the basis of the time complexity bounds.
Implementation using Qiskit: QHED on Small Images
Running on the Simulator
For the purpose of this demonstration, we can assume that an image is nothing but a collection of pixel values represented as a numpy matrix in python. Also, initially let us take only binary values for pixels for simplicity i.e. , and there are no floating point values for pixel intensities.
Later we'll see that the same algorithm can also be used with proper 8-bit B&W images.
Now that we have defined our image for testing, we can go ahead and use to encode the pixel intensities as probability amplitudes of different states of the system:-
As can be seen in the above python code, we obtain two different aplitude encoded quantum images. The first one (image_norm_h) is for the horizontal scanning of the image and the second one (image_norm_v) is for the vertical scanning of the image.
After this we initialize the number of qubits and the amplitude permutation unitary like so,
Once, we have normalized the pixel values, converted them to probability amplitudes, anc determined the number of qubits necessary for processing the image, we can start making the quantum circuit for the same.
Since, our image now basically represents the amplitudes of different quantum states, we can directly use the initialize() method to perform the state preparation. After this, we add a Hadamard gate to the auxiliary qubit, then the amplitude permutation unitary, and then again a Hadamard gate to auxiliary qubit. Also, the whole circuit is repeated once more for the vertical scanning of image.
Now, we simulate the circuits using the statevector_simulator and obtain the statevector of the system as the output.
From , we can clearly see that we need to consider only those states where the auxiliary qubit (qubit-0 or LSB in our case) gives a measurement output of . Since, we know that LSB is 1 in a bit-string only for odd numbers, we easily just take the amplitudes corresponding to odd states from the statevector to form our image and discard all the even states.
The following code, performs this task along with some classical post-processing to ensure that we get the best results when we plot our image. After we filter the required states from the raw statevector, we can rearrange the 1D array of amplitudes to a 2D matrix to get our edge detected horizontal and vertical scans like so,
Finally, we combine both horizontal and vertical scans to get the complete edge detected image as shown below,
Running on Real Hardware
This section takes a part of the previously simulated image (represented by the qc_h and qc_v) and runs them on the ibmq_santiago backend to test the running the algorithm on a real quantum computer with inherent noise and error characteristics specific to the hardware.
First we import and load our IBMQ account and select the ibmq_santiago backend.
Since, running on actual hardware deals with encountering errors due to noise, we only limit this example to run on (2+1)-qubits as of now. For the demonstration, now we can crop a part of the the above image that was used in the simulation,
Defining the parameters for the quantum circuit of the QHED algorithm and creating instances of horizontal and vertical scan circuits.
For the Horizontal and Vertical scan of the above image, we can see that the operations for state-preparation and decrement gate be written as follows:-
Horisontal Scan:
State preparation () : We can ahieve this with a simple operation.
Decrement gate: We can achieve this by a sequence of operations.
Vertical Scan:
State preparation () : We can ahieve this with a simple operation.
Decrement gate: We can achieve this by a sequence of operations.
For running the circuit on real hardware, it is necessary to decompose the above quantum circuit into the basis gates for the ibmq_santiago backend in order to run the circuit properly. To achieve this, we transpile the above circuit according to our backend's coupling map and also set the optimization_level=3, to get the most most optimized circuit according to the hardware.
Finally, we run the circuits on our backend and obtain the results shown in the histograms below,
Now, we extract the counts of the odd-numbered states from horizontal and vertical scans because only those states contain the pixel intensity gradient information in which the auxiliary qubit is in the state .
Finally, we combine both horizontal and vertical scans to make the full edge detection cropped image as shown below,
For comparison, let's simulate the quantum circuits on the qasm_simulator as well and check how the probability distribution obtained from the real hardware, differs from a perfect simulation:-
QHED on Larger Images (Exercise for the reader!)
As the quantum technology advances, we will see more and more applications related to faster image processing and image manipulation. However, for processing insanely large data like 4K images and videos, one would have to process the image in multiple parts until we reach the stage of fault-tolerant quantum hardware.
This exercise tries to incorporate a similar workflow to perform edge detection for an image which is approximately larger than out previous pixel image example. Here, you (the reader) have to load a pixel, 8-bit color, custom image and perform edge detection to it using the QHED algorithm as discussed in the previous examples. This has to be done by diving it into multiple smaller images and then combining them together at the end.
We also define an initial code snippet, which helps you to load the image and also we define a variable image_crop_size, which refers to the size of each part that this image will be divided into. Feel free to change the variables below and play around with the values to get the best balance between the size of each part of image and the total number of parts that the original image is divided into. Write your code in the cell which says ## YOUR CODE GOES HERE #####. We hope you enjoy this exercise! 😄
Hint: Since, the above image is very big to encode at once on today's devices, the solution to this problem would contain the following steps:
Find the maximum image size which is simulable on the
statevector_simulator(Try choosing a power of 2). Let us consider it to be .Divide the image into multiple parts of size
Create circuit for each part and measure the edge detected image.
Combine all the parts to get a single edge detected image of size .
The final image should like look something like this:

References
[1] Le, P.Q., Dong, F. & Hirota, K. A flexible representation of quantum images for polynomial preparation, image compression, and processing operations. Quantum Inf Process 10, 63–84 (2011). https://doi.org/10.1007/s11128-010-0177-y
[2] Zhang, Y., Lu, K., Gao, Y. et al. NEQR: a novel enhanced quantum representation of digital images. Quantum Inf Process 12, 2833–2860 (2013). https://doi.org/10.1007/s11128-013-0567-z
[3] Yao, Xi-Wei, et al. "Quantum image processing and its application to edge detection: theory and experiment." Physical Review X 7.3 (2017): 031041. https://arxiv.org/abs/1801.01465
[4] Zhang, Yi, Kai Lu, and YingHui Gao. "QSobel: a novel quantum image edge extraction algorithm." Science China Information Sciences 58.1 (2015): 1-13. https://link.springer.com/article/10.1007/s11432-014-5158-9
[5] Yan, Fei, Abdullah M. Iliyasu, and Salvador E. Venegas-Andraca. "A survey of quantum image representations." Quantum Information Processing 15.1 (2016): 1-35. https://link.springer.com/article/10.1007/s11128-015-1195-6
[6] Ruan, Yue, Xiling Xue, and Yuanxia Shen. "Quantum Image Processing: Opportunities and Challenges." Mathematical Problems in Engineering 2021 (2021). https://www.hindawi.com/journals/mpe/2021/6671613/
[7] L. Grover and T. Rudolph, "Creating Superpositions That Correspond to Efficiently Integrable Probability Distributions", https://arxiv.org/abs/quant-ph/0208112
[8] A. N. Soklakov and R. Schack, "Efficient State Preparation for a Register of Quantum Bits", Phys. Rev. A 73, 012307 (2006). https://arxiv.org/abs/quant-ph/0408045
[9] Fijany, Amir, and Colin P. Williams. "Quantum wavelet transforms: Fast algorithms and complete circuits." NASA international conference on quantum computing and quantum communications. Springer, Berlin, Heidelberg, 1998. https://arxiv.org/abs/quant-ph/9809004
[10] Craig Gidney, "Constructing Large Increment Gates". https://algassert.com/circuits/2015/06/12/Constructing-Large-Increment-Gates.html
[11] Katiyar, Sunil Kumar, and P. V. Arun. "Comparative analysis of common edge detection techniques in context of object extraction." arXiv preprint arXiv:1405.6132 (2014). https://arxiv.org/abs/1405.6132
[12] Zhang, Xiao-Ming, Man-Hong Yung, and Xiao Yuan. "Low-depth Quantum State Preparation." arXiv preprint arXiv:2102.07533 (2021). https://arxiv.org/abs/2102.07533