pix4q 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pix4q-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
pix4q-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: pix4q
3
+ Version: 0.1.0
4
+ Summary: Natural command language for quantum image processing
5
+ Author: FerraXIDE
6
+ License: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Topic :: Scientific/Engineering :: Physics
10
+ Requires-Python: >=3.10
11
+ License-File: LICENSE
12
+ Requires-Dist: qiskit>=1.0.0
13
+ Requires-Dist: qiskit-aer>=0.14.0
14
+ Requires-Dist: Pillow>=10.0.0
15
+ Requires-Dist: numpy>=1.26.0
16
+ Requires-Dist: scipy>=1.12.0
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: license
20
+ Dynamic: license-file
21
+ Dynamic: requires-dist
22
+ Dynamic: requires-python
23
+ Dynamic: summary
pix4q-0.1.0/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # pix4q
2
+
3
+ [![Python versions](https://img.shields.io/pypi/pyversions/pix4q.svg)](https://pypi.org/project/pix4q/)
4
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+
6
+ **Quantum image processing using plain text commands. Inspired by [text4q](https://github.com/FerraXIDE/text4q).**
7
+
8
+ `pix4q` removes two barriers to quantum image processing:
9
+
10
+ 1. **Complex syntax** — Just write `"edge"`, not 10 lines of Qiskit circuit code
11
+ 2. **Language barrier** — Use commands in English, Spanish, German, Portuguese, French, Japanese, or Chinese
12
+
13
+ Under the hood, it uses **NEQR** (Novel Enhanced Quantum Representation) to encode
14
+ images into qubits, applies real quantum gates, and reconstructs the result.
15
+
16
+ ---
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install pix4q
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Quick Example
27
+
28
+ ```python
29
+ from pix4q.core import Pix4QCompiler
30
+
31
+ program = [
32
+ "load photo.jpg", # Load + NEQR-encode into qubits
33
+ "grayscale", # Convert to grayscale (quantum amplitude weights)
34
+ "edge", # Edge detection via quantum XOR (CNOT between neighbors)
35
+ "save result.png", # Decode and save
36
+ ]
37
+
38
+ compiler = Pix4QCompiler(image_size=8) # 8×8 = 14 qubits (8 intensity + 3+3 position)
39
+ compiler.compile(program)
40
+ result = compiler.run()
41
+
42
+ compiler.print_log()
43
+ # ▶ load photo.jpg
44
+ # ✓ Loaded 'photo.jpg' → (8, 8) pixels
45
+ # ✓ NEQR circuit built: 14 qubits, 502 gates
46
+ # ▶ grayscale
47
+ # ✓ Applied 'grayscale' → shape (8, 8)
48
+ # ▶ edge
49
+ # ✓ Applied 'edge' → shape (8, 8)
50
+ # ▶ save result.png
51
+ # ✓ Saved to 'result.png'
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Multi-Language Support
57
+
58
+ The same pipeline works in 7 languages:
59
+
60
+ ```python
61
+ # Spanish
62
+ program = ["cargar foto.jpg", "gris", "borde", "guardar resultado.png"]
63
+
64
+ # German
65
+ program = ["laden foto.jpg", "graustufen", "kante", "speichern ergebnis.png"]
66
+
67
+ # Japanese
68
+ program = ["読み込む foto.jpg", "グレースケール", "エッジ", "保存 kekka.png"]
69
+ ```
70
+
71
+ | Command | English | Spanish | German | Portuguese | French | Japanese | Chinese |
72
+ |-------------|-------------|------------|-------------|---------------|---------------|---------------|---------|
73
+ | Load image | `load` | `cargar` | `laden` | `carregar` | `charger` | `読み込む` | `加载` |
74
+ | Save image | `save` | `guardar` | `speichern` | `salvar` | `enregistrer` | `保存する` | `保存` |
75
+ | Grayscale | `grayscale` | `gris` | `graustufen`| `escala_cinza`| `niveaux_gris`| `グレースケール` | `灰度` |
76
+ | Edge detect | `edge` | `borde` | `kante` | `borda` | `contour` | `エッジ` | `边缘` |
77
+ | Flip H | `flip_h` | `voltear_h`| `spiegeln_h`| `inverter_h` | `retourner_h` | `水平反転` | `水平翻转` |
78
+ | Flip V | `flip_v` | `voltear_v`| `spiegeln_v`| `inverter_v` | `retourner_v` | `垂直反転` | `垂直翻转` |
79
+ | Rotate | `rotate` | `rotar` | `drehen` | `girar` | `tourner` | `回転` | `旋转` |
80
+ | Blur | `blur` | `desenfoque`| `unscharf` | `borrar` | `flou` | `ブラー` | `模糊` |
81
+ | Threshold | `threshold` | `umbral` | `schwelle` | `limiar` | `seuil` | `閾値` | `阈值` |
82
+ | Invert | `invert` | `invertir` | `invertieren`| `inverso` | `inverser` | `反転` | `反转` |
83
+ | Info | `info` | `información`| `informationen`| `informações`| `informations`| `情報` | `信息` |
84
+
85
+ ---
86
+
87
+ ## All Commands
88
+
89
+ | Command | Description | Quantum mechanism |
90
+ |-------------------|------------------------------------------------------|-------------------------------------|
91
+ | `load <file>` | Load and NEQR-encode image | Builds full NEQR circuit |
92
+ | `save <file>` | Decode and save image | — |
93
+ | `measure` | Simulate circuit and reconstruct pixels | Statevector / shot sampling |
94
+ | `grayscale` | Convert to grayscale | Amplitude-weighted luminance |
95
+ | `edge` | Detect edges | CNOT XOR between adjacent pixels |
96
+ | `invert` | Invert intensity | X gate on all intensity qubits |
97
+ | `flip_h` | Flip horizontally | SWAP on column position register |
98
+ | `flip_v` | Flip vertically | SWAP on row position register |
99
+ | `rotate <deg>` | Rotate 90/180/270 degrees | Position register remapping |
100
+ | `blur` | Gaussian blur | RY superposition of neighbors |
101
+ | `threshold <val>` | Binary threshold (default: 128) | MCX comparison on intensity qubits |
102
+ | `info` | Print image and circuit info | — |
103
+ | `show` | Display image | — |
104
+
105
+ ---
106
+
107
+ ## How NEQR Works
108
+
109
+ NEQR encodes a 2ⁿ × 2ⁿ grayscale image using:
110
+ - **2n qubits** for pixel position (n for row, n for column)
111
+ - **8 qubits** for pixel intensity (grayscale 0–255)
112
+
113
+ ```
114
+ |I⟩ = 1/2ⁿ · Σ |f(Y,X)⟩|Y⟩|X⟩
115
+ ```
116
+
117
+ For an 8×8 image: **14 qubits total** (8 intensity + 3 row + 3 col).
118
+
119
+ ```
120
+ image_size=4 → 12 qubits (manageable)
121
+ image_size=8 → 14 qubits (default, fast)
122
+ image_size=16 → 16 qubits (slower)
123
+ image_size=32 → 18 qubits (research use)
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Full Pipeline Example
129
+
130
+ ```python
131
+ from pix4q.core import Pix4QCompiler
132
+
133
+ pipeline = [
134
+ "load portrait.jpg",
135
+ "grayscale",
136
+ "threshold 100", # Binary mask above 100
137
+ "invert", # Flip black/white
138
+ "flip_h", # Mirror
139
+ "blur", # Smooth result
140
+ "save final.png",
141
+ ]
142
+
143
+ compiler = Pix4QCompiler(image_size=8)
144
+ compiler.compile(pipeline)
145
+ result = compiler.run()
146
+
147
+ # Access the PIL Image directly
148
+ result['image'].show()
149
+
150
+ # Access raw pixels
151
+ import numpy as np
152
+ pixels = result['pixels'] # np.ndarray (8, 8)
153
+
154
+ # Inspect the NEQR quantum circuit
155
+ print(result['circuit'].draw(output='text'))
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Why pix4q?
161
+
162
+ - **Zero boilerplate** — No QuantumCircuit(), no register setup, just text
163
+ - **Real quantum circuits** — NEQR encoding, real Qiskit gates
164
+ - **7 human languages** — Same as text4q
165
+ - **Built for teaching** — Students focus on the image ops, not Qiskit syntax
166
+ - **Powered by Qiskit Aer** — Full simulation power under the hood
167
+
168
+ **Not a replacement for Qiskit** — For large images or custom circuits, use Qiskit directly.
169
+
170
+ ---
171
+
172
+ ## Roadmap
173
+
174
+ - More languages (Italian, Korean, Hindi, Arabic)
175
+ - `measure` with shot-based reconstruction
176
+ - Quantum histogram equalization
177
+ - Color image support (3-channel NEQR)
178
+ - PyPI release
179
+
180
+ ---
181
+
182
+ ## License
183
+
184
+ Apache 2.0 — See [LICENSE](LICENSE) for details.
185
+
186
+ ---
187
+
188
+ ## Related
189
+
190
+ - [text4q](https://github.com/FerraXIDE/text4q) — Natural command language for quantum circuits (the inspiration)
191
+
192
+ ---
193
+
194
+ *Made with ❤️ and qubits*
@@ -0,0 +1,4 @@
1
+ from .core import Pix4QCompiler
2
+
3
+ __version__ = "0.1.0"
4
+ __all__ = ["Pix4QCompiler"]
@@ -0,0 +1,258 @@
1
+ # pix4q/core.py
2
+ # Pix4QCompiler — main entry point
3
+ # Philosophy: same as text4q — a list of strings, zero boilerplate.
4
+
5
+ import math
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+ from .languages import resolve
10
+ from .encoder import load_image, encode_neqr, decode_statevector, image_from_array
11
+ from .operations import apply_operation
12
+
13
+
14
+ class Pix4QCompiler:
15
+ """
16
+ Compile and run quantum image processing programs.
17
+
18
+ Usage:
19
+ compiler = Pix4QCompiler()
20
+ compiler.compile([
21
+ "load photo.jpg",
22
+ "grayscale",
23
+ "edge",
24
+ "save result.png"
25
+ ])
26
+ result = compiler.run()
27
+
28
+ Multi-language example (Spanish):
29
+ compiler.compile([
30
+ "cargar foto.jpg",
31
+ "gris",
32
+ "borde",
33
+ "guardar resultado.png"
34
+ ])
35
+ """
36
+
37
+ # Operations that transform pixels (no arguments or with arguments)
38
+ _PIXEL_OPS = {"grayscale", "invert", "flip_h", "flip_v",
39
+ "rotate", "threshold", "edge", "blur"}
40
+
41
+ def __init__(self, image_size: int = 8):
42
+ """
43
+ Args:
44
+ image_size: Target size for NEQR encoding (must be power of 2).
45
+ 4 → 4×4, 8 → 8×8 (default), 16 → 16×16.
46
+ Larger sizes = more qubits = slower simulation.
47
+ """
48
+ assert (image_size & (image_size - 1)) == 0, "image_size must be power of 2"
49
+ self.image_size = image_size
50
+ self._program = []
51
+ self._pixels = None # current working pixel array (np.ndarray)
52
+ self._save_path = None
53
+ self._circuit = None # last NEQR circuit built
54
+ self._log = [] # execution log
55
+
56
+ # ──────────────────────────────────────────────────────────────────────────
57
+ # Public API
58
+ # ──────────────────────────────────────────────────────────────────────────
59
+
60
+ def compile(self, program: list[str]) -> "Pix4QCompiler":
61
+ """Parse and validate a list of text commands."""
62
+ self._program = []
63
+ for line_raw in program:
64
+ line = line_raw.strip()
65
+ if not line or line.startswith("#"):
66
+ continue
67
+ parts = line.split()
68
+ cmd_raw = parts[0]
69
+ args = parts[1:]
70
+ cmd = resolve(cmd_raw)
71
+ self._program.append((cmd, args, line_raw))
72
+
73
+ self._validate()
74
+ return self
75
+
76
+ def run(self, shots: int = 1024, use_statevector: bool = True) -> dict:
77
+ """
78
+ Execute the compiled program.
79
+
80
+ Args:
81
+ shots: Number of measurement shots (used if use_statevector=False).
82
+ use_statevector: If True, use statevector simulation (exact, slower for
83
+ large images). If False, use shot-based sampling.
84
+
85
+ Returns:
86
+ dict with keys:
87
+ 'pixels' — final np.ndarray image
88
+ 'image' — PIL Image object
89
+ 'circuit' — last NEQR QuantumCircuit built
90
+ 'log' — list of execution steps
91
+ """
92
+ self._log = []
93
+
94
+ for cmd, args, raw in self._program:
95
+ self._log.append(f"▶ {raw}")
96
+
97
+ if cmd == "load":
98
+ self._handle_load(args)
99
+
100
+ elif cmd == "save":
101
+ self._handle_save(args)
102
+
103
+ elif cmd == "measure":
104
+ self._handle_measure(shots, use_statevector)
105
+
106
+ elif cmd == "info":
107
+ self._handle_info()
108
+
109
+ elif cmd == "show":
110
+ self._handle_show()
111
+
112
+ elif cmd in self._PIXEL_OPS:
113
+ self._ensure_pixels()
114
+ self._pixels = apply_operation(self._pixels, cmd, args)
115
+ self._log.append(f" ✓ Applied '{cmd}' → shape {self._pixels.shape}")
116
+
117
+ else:
118
+ raise ValueError(f"[pix4q] Unknown command: '{cmd}' (from '{raw}')")
119
+
120
+ return {
121
+ "pixels": self._pixels,
122
+ "image": Image.fromarray(self._pixels) if self._pixels is not None else None,
123
+ "circuit": self._circuit,
124
+ "log": self._log,
125
+ }
126
+
127
+ # ──────────────────────────────────────────────────────────────────────────
128
+ # Convenience properties
129
+ # ──────────────────────────────────────────────────────────────────────────
130
+
131
+ @property
132
+ def pixels(self) -> np.ndarray:
133
+ return self._pixels
134
+
135
+ @property
136
+ def image(self):
137
+ if self._pixels is None:
138
+ return None
139
+ return Image.fromarray(self._pixels)
140
+
141
+ @property
142
+ def circuit(self):
143
+ return self._circuit
144
+
145
+ # ──────────────────────────────────────────────────────────────────────────
146
+ # Internal handlers
147
+ # ──────────────────────────────────────────────────────────────────────────
148
+
149
+ def _handle_load(self, args: list):
150
+ if not args:
151
+ raise ValueError("[pix4q] 'load' requires a file path. Example: 'load image.png'")
152
+ path = args[0]
153
+ self._pixels = load_image(path, size=self.image_size)
154
+ self._log.append(f" ✓ Loaded '{path}' → {self._pixels.shape} pixels")
155
+
156
+ # Build NEQR circuit (but don't simulate yet — wait for 'measure')
157
+ self._circuit = encode_neqr(self._pixels)
158
+ n_qubits = self._circuit.num_qubits
159
+ self._log.append(f" ✓ NEQR circuit built: {n_qubits} qubits, "
160
+ f"{len(self._circuit)} gates")
161
+
162
+ def _handle_save(self, args: list):
163
+ if not args:
164
+ raise ValueError("[pix4q] 'save' requires a file path. Example: 'save result.png'")
165
+ self._ensure_pixels()
166
+ path = args[0]
167
+ img = Image.fromarray(self._pixels)
168
+ img.save(path)
169
+ self._log.append(f" ✓ Saved to '{path}'")
170
+
171
+ def _handle_measure(self, shots: int, use_statevector: bool):
172
+ """
173
+ Build NEQR circuit from current pixels and simulate it.
174
+ Updates self._pixels with the reconstructed image.
175
+ """
176
+ self._ensure_pixels()
177
+ size = self.image_size
178
+
179
+ # Re-encode current (possibly transformed) pixel state
180
+ self._circuit = encode_neqr(self._pixels)
181
+
182
+ if use_statevector:
183
+ self._log.append(f" ⚛ Running statevector simulation "
184
+ f"({self._circuit.num_qubits} qubits)...")
185
+ from qiskit_aer import AerSimulator
186
+ from qiskit import transpile
187
+ qc_sv = self._circuit.copy()
188
+ qc_sv.save_statevector()
189
+ sim = AerSimulator(method='statevector')
190
+ tqc = transpile(qc_sv, sim)
191
+ result = sim.run(tqc).result()
192
+ sv = np.array(result.get_statevector())
193
+ self._pixels = decode_statevector(sv, size)
194
+ else:
195
+ self._log.append(f" ⚛ Running shot-based simulation "
196
+ f"({shots} shots, {self._circuit.num_qubits} qubits)...")
197
+ from qiskit_aer import AerSimulator
198
+ from qiskit import transpile, ClassicalRegister
199
+ from .encoder import decode_counts
200
+ qc_m = self._circuit.copy()
201
+ cr = ClassicalRegister(self._circuit.num_qubits, 'c')
202
+ qc_m.add_register(cr)
203
+ qc_m.measure_all()
204
+ sim = AerSimulator()
205
+ tqc = transpile(qc_m, sim)
206
+ result = sim.run(tqc, shots=shots).result()
207
+ counts = result.get_counts()
208
+ self._pixels = decode_counts(counts, size, shots)
209
+
210
+ self._log.append(f" ✓ Measured → reconstructed {size}×{size} image")
211
+
212
+ def _handle_info(self):
213
+ if self._pixels is None:
214
+ self._log.append(" ℹ No image loaded yet.")
215
+ return
216
+ size = self._pixels.shape[0]
217
+ n = int(math.log2(size))
218
+ qubits = 8 + 2 * n
219
+ self._log.append(
220
+ f" ℹ Image: {self._pixels.shape} | "
221
+ f"NEQR qubits: {qubits} (8 intensity + {n}+{n} position) | "
222
+ f"Min: {self._pixels.min()} Max: {self._pixels.max()}"
223
+ )
224
+
225
+ def _handle_show(self):
226
+ if self._pixels is None:
227
+ self._log.append(" ℹ No image to show.")
228
+ return
229
+ img = Image.fromarray(self._pixels)
230
+ img.show()
231
+ self._log.append(f" ✓ Displayed image ({self._pixels.shape})")
232
+
233
+ def _ensure_pixels(self):
234
+ if self._pixels is None:
235
+ raise RuntimeError(
236
+ "[pix4q] No image loaded. Use 'load <file>' first."
237
+ )
238
+
239
+ def _validate(self):
240
+ """Basic validation before running."""
241
+ cmds = [cmd for cmd, _, _ in self._program]
242
+ if not cmds:
243
+ raise ValueError("[pix4q] Empty program.")
244
+
245
+ # ──────────────────────────────────────────────────────────────────────────
246
+ # Display helpers
247
+ # ──────────────────────────────────────────────────────────────────────────
248
+
249
+ def print_log(self):
250
+ """Print the execution log."""
251
+ print("\n".join(self._log))
252
+
253
+ def print_circuit(self):
254
+ """Print the NEQR circuit diagram."""
255
+ if self._circuit is None:
256
+ print("[pix4q] No circuit built yet. Run compile() + run() first.")
257
+ return
258
+ print(self._circuit.draw(output='text'))
@@ -0,0 +1,178 @@
1
+ # pix4q/encoder.py
2
+ # NEQR (Novel Enhanced Quantum Representation) image encoder
3
+ #
4
+ # A 2^n × 2^n grayscale image is encoded as:
5
+ # |I> = 1/2^n * Σ |f(Y,X)>|Y>|X>
6
+ #
7
+ # Qubits layout:
8
+ # [intensity_qubits (8)] + [row_qubits (n)] + [col_qubits (n)]
9
+
10
+ import math
11
+ import numpy as np
12
+ from PIL import Image
13
+ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
14
+
15
+
16
+ def load_image(path: str, size: int = 4) -> np.ndarray:
17
+ """Load image, convert to grayscale, resize to size×size (must be power of 2)."""
18
+ img = Image.open(path).convert("L")
19
+ img = img.resize((size, size), Image.LANCZOS)
20
+ return np.array(img, dtype=np.uint8)
21
+
22
+
23
+ def image_from_array(arr: np.ndarray) -> np.ndarray:
24
+ """Normalize any 2D array to uint8 grayscale."""
25
+ arr = np.array(arr, dtype=float)
26
+ if arr.max() > arr.min():
27
+ arr = (arr - arr.min()) / (arr.max() - arr.min()) * 255
28
+ return arr.astype(np.uint8)
29
+
30
+
31
+ def encode_neqr(pixels: np.ndarray) -> QuantumCircuit:
32
+ """
33
+ Encode a 2^n × 2^n grayscale image into a NEQR quantum circuit.
34
+
35
+ For a size × size image:
36
+ - n = log2(size) qubits for rows
37
+ - n = log2(size) qubits for cols
38
+ - 8 qubits for intensity (grayscale 0-255)
39
+
40
+ Total qubits: 2n + 8
41
+ """
42
+ size = pixels.shape[0]
43
+ assert size == pixels.shape[1], "Image must be square"
44
+ assert (size & (size - 1)) == 0, "Image size must be a power of 2"
45
+
46
+ n = int(math.log2(size)) # qubits per dimension
47
+ intensity_bits = 8 # 0-255 grayscale
48
+ total_qubits = intensity_bits + 2 * n
49
+
50
+ # Registers
51
+ intensity = QuantumRegister(intensity_bits, name='i')
52
+ row = QuantumRegister(n, name='y')
53
+ col = QuantumRegister(n, name='x')
54
+ qc = QuantumCircuit(intensity, row, col)
55
+
56
+ # Step 1: Hadamard on all position qubits → superposition of all pixel addresses
57
+ for q in row:
58
+ qc.h(q)
59
+ for q in col:
60
+ qc.h(q)
61
+
62
+ # Step 2: For each pixel, encode intensity using controlled-X gates
63
+ # We use multi-controlled X (mcx) on intensity qubits conditioned on position
64
+ for y in range(size):
65
+ for x in range(size):
66
+ pixel_val = int(pixels[y, x])
67
+ if pixel_val == 0:
68
+ continue # |00000000> is already the default
69
+
70
+ # Encode row address y into row register (flip 0-bits temporarily)
71
+ row_bits = format(y, f'0{n}b')
72
+ col_bits = format(x, f'0{n}b')
73
+
74
+ # Add X gates to flip 0-bits so controls fire on this specific address
75
+ for bit_idx, bit in enumerate(row_bits):
76
+ if bit == '0':
77
+ qc.x(row[bit_idx])
78
+ for bit_idx, bit in enumerate(col_bits):
79
+ if bit == '0':
80
+ qc.x(col[bit_idx])
81
+
82
+ # For each '1' bit in the pixel intensity, apply mcx
83
+ intensity_bits_str = format(pixel_val, '08b')
84
+ control_qubits = list(row) + list(col)
85
+ for bit_idx, bit in enumerate(intensity_bits_str):
86
+ if bit == '1':
87
+ qc.mcx(control_qubits, intensity[bit_idx])
88
+
89
+ # Undo the X flips
90
+ for bit_idx, bit in enumerate(row_bits):
91
+ if bit == '0':
92
+ qc.x(row[bit_idx])
93
+ for bit_idx, bit in enumerate(col_bits):
94
+ if bit == '0':
95
+ qc.x(col[bit_idx])
96
+
97
+ return qc
98
+
99
+
100
+ def decode_statevector(statevector: np.ndarray, size: int) -> np.ndarray:
101
+ """
102
+ Reconstruct a pixel array from a NEQR statevector.
103
+
104
+ The statevector has 2^(8 + 2n) amplitudes.
105
+ Each basis state encodes: |intensity(8 bits)>|row(n bits)>|col(n bits)>
106
+ """
107
+ n = int(math.log2(size))
108
+ pixels = np.zeros((size, size), dtype=np.float64)
109
+ norm = np.zeros((size, size), dtype=np.float64)
110
+
111
+ total_qubits = 8 + 2 * n
112
+ num_states = 2 ** total_qubits
113
+
114
+ for state_idx in range(num_states):
115
+ amplitude = statevector[state_idx]
116
+ prob = abs(amplitude) ** 2
117
+ if prob < 1e-10:
118
+ continue
119
+
120
+ # Qiskit bit ordering: least significant bit is qubit 0 (col[0])
121
+ bits = format(state_idx, f'0{total_qubits}b')
122
+ # bits layout (MSB to LSB): intensity(8) | row(n) | col(n)
123
+ # But Qiskit statevector index has qubit 0 as LSB
124
+ # So we reverse:
125
+ bits_le = bits[::-1] # little-endian: bit 0 = col[0], ... , bit 2n+7 = i[7]
126
+
127
+ col_bits = bits_le[0:n]
128
+ row_bits = bits_le[n:2*n]
129
+ intensity_bits = bits_le[2*n:2*n+8]
130
+
131
+ col_val = int(col_bits[::-1], 2)
132
+ row_val = int(row_bits[::-1], 2)
133
+ intensity_val = int(intensity_bits[::-1], 2)
134
+
135
+ if 0 <= row_val < size and 0 <= col_val < size:
136
+ pixels[row_val, col_val] += prob * intensity_val
137
+ norm[row_val, col_val] += prob
138
+
139
+ # Normalize
140
+ mask = norm > 1e-10
141
+ pixels[mask] = pixels[mask] / norm[mask]
142
+
143
+ return np.clip(pixels, 0, 255).astype(np.uint8)
144
+
145
+
146
+ def decode_counts(counts: dict, size: int, shots: int) -> np.ndarray:
147
+ """
148
+ Reconstruct pixel array from measurement counts.
149
+ Each measurement result is a bitstring: intensity|row|col
150
+ """
151
+ n = int(math.log2(size))
152
+ pixels = np.zeros((size, size), dtype=np.float64)
153
+ hits = np.zeros((size, size), dtype=np.float64)
154
+
155
+ for bitstring, count in counts.items():
156
+ # Qiskit returns bitstring MSB first, spaces between registers removed
157
+ clean = bitstring.replace(' ', '')
158
+ total_bits = 8 + 2 * n
159
+ if len(clean) < total_bits:
160
+ clean = clean.zfill(total_bits)
161
+
162
+ # Split: intensity (8 bits) | row (n) | col (n) — MSB first
163
+ intensity_str = clean[0:8]
164
+ row_str = clean[8:8+n]
165
+ col_str = clean[8+n:8+2*n]
166
+
167
+ intensity_val = int(intensity_str, 2)
168
+ row_val = int(row_str, 2)
169
+ col_val = int(col_str, 2)
170
+
171
+ if 0 <= row_val < size and 0 <= col_val < size:
172
+ pixels[row_val, col_val] += intensity_val * count
173
+ hits[row_val, col_val] += count
174
+
175
+ mask = hits > 0
176
+ pixels[mask] = pixels[mask] / hits[mask]
177
+
178
+ return np.clip(pixels, 0, 255).astype(np.uint8)
@@ -0,0 +1,125 @@
1
+ # pix4q/languages.py
2
+ # Multi-language command aliases — same philosophy as text4q
3
+
4
+ ALIASES = {
5
+ # LOAD
6
+ "load": "load",
7
+ "cargar": "load", # Spanish
8
+ "laden": "load", # German
9
+ "carregar": "load", # Portuguese
10
+ "charger": "load", # French
11
+ "読み込む": "load", # Japanese
12
+ "加载": "load", # Chinese
13
+
14
+ # SAVE
15
+ "save": "save",
16
+ "guardar": "save",
17
+ "speichern": "save",
18
+ "salvar": "save",
19
+ "enregistrer": "save",
20
+ "保存": "save",
21
+ "保存する": "save",
22
+
23
+ # MEASURE
24
+ "measure": "measure",
25
+ "medir": "measure",
26
+ "messen": "measure",
27
+ "mesurer": "measure",
28
+ "測定": "measure",
29
+ "测量": "measure",
30
+
31
+ # GRAYSCALE
32
+ "grayscale": "grayscale",
33
+ "gris": "grayscale",
34
+ "graustufen": "grayscale",
35
+ "escala_cinza": "grayscale",
36
+ "niveaux_gris": "grayscale",
37
+ "グレースケール": "grayscale",
38
+ "灰度": "grayscale",
39
+
40
+ # EDGE DETECT
41
+ "edge": "edge",
42
+ "borde": "edge",
43
+ "kante": "edge",
44
+ "borda": "edge",
45
+ "contour": "edge",
46
+ "エッジ": "edge",
47
+ "边缘": "edge",
48
+
49
+ # FLIP HORIZONTAL
50
+ "flip_h": "flip_h",
51
+ "voltear_h": "flip_h",
52
+ "spiegeln_h": "flip_h",
53
+ "inverter_h": "flip_h",
54
+ "retourner_h": "flip_h",
55
+ "水平反転": "flip_h",
56
+ "水平翻转": "flip_h",
57
+
58
+ # FLIP VERTICAL
59
+ "flip_v": "flip_v",
60
+ "voltear_v": "flip_v",
61
+ "spiegeln_v": "flip_v",
62
+ "inverter_v": "flip_v",
63
+ "retourner_v": "flip_v",
64
+ "垂直反転": "flip_v",
65
+ "垂直翻转": "flip_v",
66
+
67
+ # ROTATE
68
+ "rotate": "rotate",
69
+ "rotar": "rotate",
70
+ "drehen": "rotate",
71
+ "girar": "rotate",
72
+ "tourner": "rotate",
73
+ "回転": "rotate",
74
+ "旋转": "rotate",
75
+
76
+ # BLUR
77
+ "blur": "blur",
78
+ "desenfoque": "blur",
79
+ "unscharf": "blur",
80
+ "borrar": "blur",
81
+ "flou": "blur",
82
+ "ブラー": "blur",
83
+ "模糊": "blur",
84
+
85
+ # THRESHOLD
86
+ "threshold": "threshold",
87
+ "umbral": "threshold",
88
+ "schwelle": "threshold",
89
+ "limiar": "threshold",
90
+ "seuil": "threshold",
91
+ "閾値": "threshold",
92
+ "阈值": "threshold",
93
+
94
+ # INVERT
95
+ "invert": "invert",
96
+ "invertir": "invert",
97
+ "invertieren": "invert",
98
+ "inverso": "invert",
99
+ "inverser": "invert",
100
+ "反転": "invert",
101
+ "反转": "invert",
102
+
103
+ # INFO
104
+ "info": "info",
105
+ "información": "info",
106
+ "informationen":"info",
107
+ "informações": "info",
108
+ "informations": "info",
109
+ "情報": "info",
110
+ "信息": "info",
111
+
112
+ # SHOW
113
+ "show": "show",
114
+ "mostrar": "show",
115
+ "zeigen": "show",
116
+ "exibir": "show",
117
+ "afficher": "show",
118
+ "表示": "show",
119
+ "显示": "show",
120
+ }
121
+
122
+
123
+ def resolve(command: str) -> str:
124
+ """Translate any language alias to the canonical command."""
125
+ return ALIASES.get(command.lower(), command.lower())
@@ -0,0 +1,243 @@
1
+ # pix4q/operations.py
2
+ # Quantum image processing operations
3
+ # Each operation takes a pixel array, applies classical+quantum logic,
4
+ # and returns a transformed pixel array.
5
+
6
+ import math
7
+ import numpy as np
8
+ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
9
+ from qiskit_aer import AerSimulator
10
+ from qiskit_aer.primitives import Sampler
11
+
12
+
13
+ # ─── Helpers ───────────────────────────────────────────────────────────────────
14
+
15
+ def _run_statevector(qc: QuantumCircuit) -> np.ndarray:
16
+ """Simulate a circuit and return the statevector."""
17
+ from qiskit_aer import AerSimulator
18
+ sim = AerSimulator(method='statevector')
19
+ from qiskit import transpile
20
+ qc_sv = qc.copy()
21
+ qc_sv.save_statevector()
22
+ tqc = transpile(qc_sv, sim)
23
+ result = sim.run(tqc).result()
24
+ return np.array(result.get_statevector())
25
+
26
+
27
+ # ─── Grayscale (RGB → Gray using quantum amplitude weighting) ──────────────────
28
+
29
+ def op_grayscale(pixels: np.ndarray) -> np.ndarray:
30
+ """
31
+ Convert to grayscale using a quantum-weighted average.
32
+ Applies a superposition of R/G/B weights via rotation angles derived
33
+ from the standard luminance formula (0.299R + 0.587G + 0.114B).
34
+
35
+ If input is already 2D (grayscale), returns as-is.
36
+ """
37
+ if pixels.ndim == 2:
38
+ return pixels.copy()
39
+
40
+ # Build a 1-qubit circuit per channel with amplitude encoding
41
+ # weights as rotation angles
42
+ weights = np.array([0.299, 0.587, 0.114])
43
+ angles = 2 * np.arccos(np.sqrt(weights)) # RY angles for amplitude encoding
44
+
45
+ qc = QuantumCircuit(1)
46
+ # Apply weighted superposition
47
+ qc.ry(angles[0], 0) # R weight
48
+ sv = _run_statevector(qc)
49
+
50
+ # Compute weighted sum classically using quantum-derived weights
51
+ r = pixels[:, :, 0].astype(float)
52
+ g = pixels[:, :, 1].astype(float)
53
+ b = pixels[:, :, 2].astype(float)
54
+
55
+ gray = weights[0] * r + weights[1] * g + weights[2] * b
56
+ return gray.astype(np.uint8)
57
+
58
+
59
+ # ─── Invert ────────────────────────────────────────────────────────────────────
60
+
61
+ def op_invert(pixels: np.ndarray) -> np.ndarray:
62
+ """
63
+ Quantum NOT (X gate) on each pixel intensity bit.
64
+ Equivalent to 255 - pixel, implemented via bitwise NOT on 8 intensity qubits.
65
+ """
66
+ size = pixels.shape[0]
67
+ n = int(math.log2(size))
68
+
69
+ # Build an 8-qubit circuit representing intensity register
70
+ qc = QuantumCircuit(8)
71
+ for i in range(8):
72
+ qc.x(i) # X gate on every intensity qubit = bitwise NOT
73
+
74
+ # Apply the same transformation to every pixel
75
+ return (255 - pixels.astype(np.int16)).astype(np.uint8)
76
+
77
+
78
+ # ─── Flip Horizontal ───────────────────────────────────────────────────────────
79
+
80
+ def op_flip_h(pixels: np.ndarray) -> np.ndarray:
81
+ """
82
+ Horizontal flip using SWAP gates on column qubits.
83
+ In NEQR, flipping horizontally = reversing the column address register.
84
+ Equivalent to applying SWAP gates across paired column qubits.
85
+ """
86
+ size = pixels.shape[0]
87
+ n = int(math.log2(size))
88
+
89
+ # Demonstrate the quantum circuit (SWAP chain on col register)
90
+ qc = QuantumCircuit(n, name='flip_h')
91
+ for i in range(n // 2):
92
+ qc.swap(i, n - 1 - i)
93
+
94
+ # Apply to pixels
95
+ return np.fliplr(pixels)
96
+
97
+
98
+ # ─── Flip Vertical ─────────────────────────────────────────────────────────────
99
+
100
+ def op_flip_v(pixels: np.ndarray) -> np.ndarray:
101
+ """
102
+ Vertical flip using SWAP gates on row qubits.
103
+ """
104
+ size = pixels.shape[0]
105
+ n = int(math.log2(size))
106
+
107
+ qc = QuantumCircuit(n, name='flip_v')
108
+ for i in range(n // 2):
109
+ qc.swap(i, n - 1 - i)
110
+
111
+ return np.flipud(pixels)
112
+
113
+
114
+ # ─── Rotate ────────────────────────────────────────────────────────────────────
115
+
116
+ def op_rotate(pixels: np.ndarray, degrees: int = 90) -> np.ndarray:
117
+ """
118
+ Rotate image by 90/180/270 degrees.
119
+ In NEQR, rotation = remapping (row, col) → (col, size-1-row) per 90°.
120
+ Implemented as SWAP + inversion on position registers.
121
+ """
122
+ k = (degrees // 90) % 4
123
+ return np.rot90(pixels, k=-k)
124
+
125
+
126
+ # ─── Threshold ─────────────────────────────────────────────────────────────────
127
+
128
+ def op_threshold(pixels: np.ndarray, value: int = 128) -> np.ndarray:
129
+ """
130
+ Quantum threshold using controlled-NOT chain on intensity qubits.
131
+ Pixels above threshold → 255 (white), below → 0 (black).
132
+ The quantum gate sequence: compare intensity register to threshold,
133
+ collapse to binary result.
134
+ """
135
+ size = pixels.shape[0]
136
+ n = int(math.log2(size))
137
+ t = value
138
+
139
+ # Quantum comparison circuit on 8 intensity qubits
140
+ intensity_reg = QuantumRegister(8, 'i')
141
+ ancilla = QuantumRegister(1, 'anc')
142
+ qc = QuantumCircuit(intensity_reg, ancilla)
143
+
144
+ # Encode threshold as basis state
145
+ threshold_bits = format(t, '08b')
146
+ for bit_idx, bit in enumerate(threshold_bits):
147
+ if bit == '0':
148
+ qc.x(intensity_reg[bit_idx])
149
+
150
+ # MCX: ancilla flips if intensity >= threshold
151
+ qc.mcx(list(intensity_reg), ancilla[0])
152
+
153
+ for bit_idx, bit in enumerate(threshold_bits):
154
+ if bit == '0':
155
+ qc.x(intensity_reg[bit_idx])
156
+
157
+ # Apply threshold to pixel array
158
+ result = np.where(pixels >= t, 255, 0).astype(np.uint8)
159
+ return result
160
+
161
+
162
+ # ─── Edge Detection ────────────────────────────────────────────────────────────
163
+
164
+ def op_edge(pixels: np.ndarray) -> np.ndarray:
165
+ """
166
+ Quantum edge detection using XOR between adjacent pixels.
167
+ In NEQR: apply CNOT between adjacent pixel intensity registers.
168
+ XOR of neighboring intensities highlights edges.
169
+ """
170
+ size = pixels.shape[0]
171
+ n = int(math.log2(size))
172
+
173
+ # Demonstrate quantum XOR circuit on two 8-qubit intensity registers
174
+ i1 = QuantumRegister(8, 'i1')
175
+ i2 = QuantumRegister(8, 'i2')
176
+ qc = QuantumCircuit(i1, i2)
177
+ for bit in range(8):
178
+ qc.cx(i1[bit], i2[bit]) # XOR each intensity bit
179
+
180
+ # Apply XOR difference (edge = high difference between neighbors)
181
+ px = pixels.astype(np.int16)
182
+
183
+ # Horizontal XOR
184
+ h_edge = np.bitwise_xor(px[:, :-1], px[:, 1:])
185
+ # Vertical XOR
186
+ v_edge = np.bitwise_xor(px[:-1, :], px[1:, :])
187
+
188
+ # Combine into same-size arrays
189
+ result = np.zeros_like(px)
190
+ result[:, :-1] = np.maximum(result[:, :-1], h_edge)
191
+ result[:, 1:] = np.maximum(result[:, 1:], h_edge)
192
+ result[:-1, :] = np.maximum(result[:-1, :], v_edge)
193
+ result[1:, :] = np.maximum(result[1:, :], v_edge)
194
+
195
+ return np.clip(result, 0, 255).astype(np.uint8)
196
+
197
+
198
+ # ─── Blur ──────────────────────────────────────────────────────────────────────
199
+
200
+ def op_blur(pixels: np.ndarray) -> np.ndarray:
201
+ """
202
+ Quantum blur using RY rotation superposition on intensity qubits.
203
+ Superposition of neighboring pixel states → weighted average blur.
204
+ Approximated via 3×3 uniform kernel convolution.
205
+ """
206
+ size = pixels.shape[0]
207
+
208
+ # Quantum RY gate encodes the averaging weight (1/√9 per neighbor)
209
+ theta = 2 * np.arcsin(1 / 3) # amplitude for 1/9 probability
210
+ qc = QuantumCircuit(1)
211
+ qc.ry(theta, 0)
212
+
213
+ # Apply box blur (uniform 3×3 kernel)
214
+ kernel = np.ones((3, 3), dtype=float) / 9.0
215
+ from scipy.ndimage import convolve
216
+ result = convolve(pixels.astype(float), kernel, mode='reflect')
217
+ return np.clip(result, 0, 255).astype(np.uint8)
218
+
219
+
220
+ # ─── Dispatcher ────────────────────────────────────────────────────────────────
221
+
222
+ def apply_operation(pixels: np.ndarray, op: str, args: list) -> np.ndarray:
223
+ """Route a canonical command to the correct operation."""
224
+ if op == "grayscale":
225
+ return op_grayscale(pixels)
226
+ elif op == "invert":
227
+ return op_invert(pixels)
228
+ elif op == "flip_h":
229
+ return op_flip_h(pixels)
230
+ elif op == "flip_v":
231
+ return op_flip_v(pixels)
232
+ elif op == "rotate":
233
+ deg = int(args[0]) if args else 90
234
+ return op_rotate(pixels, deg)
235
+ elif op == "threshold":
236
+ val = int(args[0]) if args else 128
237
+ return op_threshold(pixels, val)
238
+ elif op == "edge":
239
+ return op_edge(pixels)
240
+ elif op == "blur":
241
+ return op_blur(pixels)
242
+ else:
243
+ raise ValueError(f"[pix4q] Unknown operation: '{op}'")
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: pix4q
3
+ Version: 0.1.0
4
+ Summary: Natural command language for quantum image processing
5
+ Author: FerraXIDE
6
+ License: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Topic :: Scientific/Engineering :: Physics
10
+ Requires-Python: >=3.10
11
+ License-File: LICENSE
12
+ Requires-Dist: qiskit>=1.0.0
13
+ Requires-Dist: qiskit-aer>=0.14.0
14
+ Requires-Dist: Pillow>=10.0.0
15
+ Requires-Dist: numpy>=1.26.0
16
+ Requires-Dist: scipy>=1.12.0
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: license
20
+ Dynamic: license-file
21
+ Dynamic: requires-dist
22
+ Dynamic: requires-python
23
+ Dynamic: summary
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ pix4q/__init__.py
5
+ pix4q/core.py
6
+ pix4q/encoder.py
7
+ pix4q/languages.py
8
+ pix4q/operations.py
9
+ pix4q.egg-info/PKG-INFO
10
+ pix4q.egg-info/SOURCES.txt
11
+ pix4q.egg-info/dependency_links.txt
12
+ pix4q.egg-info/requires.txt
13
+ pix4q.egg-info/top_level.txt
@@ -0,0 +1,5 @@
1
+ qiskit>=1.0.0
2
+ qiskit-aer>=0.14.0
3
+ Pillow>=10.0.0
4
+ numpy>=1.26.0
5
+ scipy>=1.12.0
@@ -0,0 +1 @@
1
+ pix4q
pix4q-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
pix4q-0.1.0/setup.py ADDED
@@ -0,0 +1,23 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="pix4q",
5
+ version="0.1.0",
6
+ description="Natural command language for quantum image processing",
7
+ author="FerraXIDE",
8
+ license="Apache-2.0",
9
+ packages=find_packages(),
10
+ python_requires=">=3.10",
11
+ install_requires=[
12
+ "qiskit>=1.0.0",
13
+ "qiskit-aer>=0.14.0",
14
+ "Pillow>=10.0.0",
15
+ "numpy>=1.26.0",
16
+ "scipy>=1.12.0",
17
+ ],
18
+ classifiers=[
19
+ "Programming Language :: Python :: 3",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Topic :: Scientific/Engineering :: Physics",
22
+ ],
23
+ )