├── .gitignore
├── IMG_3895.jpeg
├── IMG_3895.png
├── LICENSE
├── README.md
├── base.jpg
├── docs
├── 12caad0293628ecba879cd580924a107.webp
└── 924c5d89cc5badfce0f16963e649b6db.webp
└── src
├── camera.py
├── detector
└── sift.py
└── main.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Editors
2 | .vscode/
3 | .idea/
4 |
5 | # Vagrant
6 | .vagrant/
7 |
8 | # Mac/OSX
9 | .DS_Store
10 |
11 | # Windows
12 | Thumbs.db
13 |
14 | # Source for the following rules: https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore
15 | # Byte-compiled / optimized / DLL files
16 | __pycache__/
17 | *.py[cod]
18 | *$py.class
19 |
20 | # C extensions
21 | *.so
22 |
23 | # Distribution / packaging
24 | .Python
25 | build/
26 | develop-eggs/
27 | dist/
28 | downloads/
29 | eggs/
30 | .eggs/
31 | lib/
32 | lib64/
33 | parts/
34 | sdist/
35 | var/
36 | wheels/
37 | *.egg-info/
38 | .installed.cfg
39 | *.egg
40 | MANIFEST
41 |
42 | # PyInstaller
43 | # Usually these files are written by a python script from a template
44 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
45 | *.manifest
46 | *.spec
47 |
48 | # Installer logs
49 | pip-log.txt
50 | pip-delete-this-directory.txt
51 |
52 | # Unit test / coverage reports
53 | htmlcov/
54 | .tox/
55 | .nox/
56 | .coverage
57 | .coverage.*
58 | .cache
59 | nosetests.xml
60 | coverage.xml
61 | *.cover
62 | .hypothesis/
63 | .pytest_cache/
64 |
65 | # Translations
66 | *.mo
67 | *.pot
68 |
69 | # Django stuff:
70 | *.log
71 | local_settings.py
72 | db.sqlite3
73 |
74 | # Flask stuff:
75 | instance/
76 | .webassets-cache
77 |
78 | # Scrapy stuff:
79 | .scrapy
80 |
81 | # Sphinx documentation
82 | docs/_build/
83 |
84 | # PyBuilder
85 | target/
86 |
87 | # Jupyter Notebook
88 | .ipynb_checkpoints
89 |
90 | # IPython
91 | profile_default/
92 | ipython_config.py
93 |
94 | # pyenv
95 | .python-version
96 |
97 | # celery beat schedule file
98 | celerybeat-schedule
99 |
100 | # SageMath parsed files
101 | *.sage.py
102 |
103 | # Environments
104 | .env
105 | .venv
106 | env/
107 | venv/
108 | ENV/
109 | env.bak/
110 | venv.bak/
111 |
112 | # Spyder project settings
113 | .spyderproject
114 | .spyproject
115 |
116 | # Rope project settings
117 | .ropeproject
118 |
119 | # mkdocs documentation
120 | /site
121 |
122 | # mypy
123 | .mypy_cache/
124 | .dmypy.json
125 | dmypy.json
126 |
127 | # Microsoft Office Temp Files
128 | ~$*
129 |
--------------------------------------------------------------------------------
/IMG_3895.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ddrpa/jigsight/ec854fb4f180bec4d529f53eeebeeff02dc67817/IMG_3895.jpeg
--------------------------------------------------------------------------------
/IMG_3895.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ddrpa/jigsight/ec854fb4f180bec4d529f53eeebeeff02dc67817/IMG_3895.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JigSight 拼图辅助
2 |
3 | 基于计算机视觉的拼图辅助系统,帮助用户快速找到拼图碎片在原图中的位置和正确的旋转角度。
4 |
5 | 
6 |
7 | ## 功能特点
8 |
9 | - 实时摄像头捕获拼图碎片
10 | - 使用 SIFT 算法进行特征匹配
11 | - 自动计算拼图碎片的旋转角度,别管对不对了
12 | - 显示处理过程
13 |
14 | ## 怎样使用
15 |
16 | 预先准备:
17 |
18 | - 拼图的原图
19 | - 摄像头
20 | - 一个和拼图有明显区分的背景,最好是纯色的
21 | - 最好有一个和完成品比例一致的印刷版参考图
22 |
23 | 
24 |
25 | 这只是个 MVP,你可能需要掌握一点点 Python 知识。
26 |
27 | - 在 `src.main.main` 中修改原图 `base_img` 的路径
28 | - 如果你有多个摄像头,在 `src.main.main` 中修改摄像头的索引 `camera_index`
29 | - 启动 `main.py`
30 |
31 | 主窗口分为四个区域:
32 |
33 | - 左侧:显示原图并使用紫色圆点和绿色框标记匹配区域
34 | - 右上:摄像头实时捕获的画面
35 | - 右中:带掩膜的拼图片
36 | - 右下:匹配成功时显示正确旋转后的拼图片
37 |
38 | 调试:
39 |
40 | - 如果拼图片的掩膜计算效果不佳,调整 `src.camera.create_mask` 的几个参数
41 | - 手动调整摄像头的焦距、感光度、快门速度等参数能够获得更稳定的结果
42 | - 如果你的拼图缺乏特征点(就像我这个的右半边一样),建议使用基于边缘匹配的方案,如 [Kawaboongawa / Zolver](https://github.com/Kawaboongawa/Zolver)
43 |
44 | ## 故事
45 |
46 | 我购入的这款 500 片拼图名为《色达雪景》,原图来自米拍摄影社区的摄影师 Rarobin。
47 |
48 | 色达县是中国四川省甘孜藏族自治州辖县,位于甘孜州东北部,面积 9338.98 平方公里。常住人口 64681 人,「色达」一词意为「金马」。
49 |
--------------------------------------------------------------------------------
/base.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ddrpa/jigsight/ec854fb4f180bec4d529f53eeebeeff02dc67817/base.jpg
--------------------------------------------------------------------------------
/docs/12caad0293628ecba879cd580924a107.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ddrpa/jigsight/ec854fb4f180bec4d529f53eeebeeff02dc67817/docs/12caad0293628ecba879cd580924a107.webp
--------------------------------------------------------------------------------
/docs/924c5d89cc5badfce0f16963e649b6db.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ddrpa/jigsight/ec854fb4f180bec4d529f53eeebeeff02dc67817/docs/924c5d89cc5badfce0f16963e649b6db.webp
--------------------------------------------------------------------------------
/src/camera.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import time
3 | import numpy as np
4 |
5 |
6 | def create_mask(image, blur_size=15, threshold_value=8, morph_size=15):
7 | """
8 | 为拼图块创建掩膜,排除边缘区域
9 | Args:
10 | image: 输入图像
11 | blur_size: 高斯模糊核大小
12 | threshold_value: 阈值化参数
13 | morph_size: 形态学操作核大小
14 | Returns:
15 | 内部区域掩膜
16 | """
17 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
18 | blurred = cv2.GaussianBlur(gray, (blur_size, blur_size), 0)
19 | edges = cv2.Canny(blurred, threshold_value, threshold_value * 3)
20 | kernel = np.ones((3, 3), np.uint8)
21 | dilated_edges = cv2.dilate(edges, kernel, iterations=2)
22 | contours, _ = cv2.findContours(dilated_edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
23 | mask = np.zeros_like(gray)
24 |
25 | if contours:
26 | # 找到最大轮廓(假设是拼图块的边界)
27 | max_contour = max(contours, key=cv2.contourArea)
28 | # 填充轮廓内部
29 | cv2.drawContours(mask, [max_contour], 0, 255, -1)
30 | # 腐蚀掩膜,去除边缘区域
31 | morph_kernel = np.ones((morph_size, morph_size), np.uint8)
32 | mask = cv2.erode(mask, morph_kernel, iterations=1)
33 | return mask
34 |
35 |
36 | def open_camera(camera_index, crop_ratio, callback):
37 | cv2.destroyAllWindows()
38 | time.sleep(0.2)
39 | cap = cv2.VideoCapture(camera_index)
40 | if not cap.isOpened():
41 | print(f"ERROR: camera {camera_index} can not open")
42 | return
43 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
44 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
45 | crop_width = int(width * crop_ratio)
46 | crop_height = int(height * crop_ratio)
47 | start_x = (width - crop_width) // 2
48 | start_y = (height - crop_height) // 2
49 | end_x = start_x + crop_width
50 | end_y = start_y + crop_height
51 |
52 | print(f"camera {camera_index} on")
53 | print(f"crop ratio: {int(crop_ratio * 100)}%")
54 | print("press ESC to exit")
55 |
56 | try:
57 | while True:
58 | ret, frame = cap.read()
59 | if not ret:
60 | print("ERROR: Unable to capture image")
61 | break
62 | center_area = frame[start_y:end_y, start_x:end_x].copy()
63 | mask = create_mask(center_area)
64 | if callback:
65 | callback(center_area, mask)
66 | key = cv2.waitKey(1)
67 | if key == 27: # ESC
68 | print("exit")
69 | break
70 | finally:
71 | cap.release()
72 | cv2.destroyAllWindows()
73 | time.sleep(0.2)
74 |
--------------------------------------------------------------------------------
/src/detector/sift.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 |
4 |
5 | def preprocess(img):
6 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
7 | blurred = cv2.GaussianBlur(gray, (5, 5), 0)
8 | return blurred
9 |
10 |
11 | def match_with_sift(base_image, gray_base, piece, mask):
12 | sift = cv2.SIFT_create()
13 | gray_piece = preprocess(piece)
14 |
15 | kp1, des1 = sift.detectAndCompute(gray_piece, mask)
16 | kp2, des2 = sift.detectAndCompute(gray_base, None)
17 |
18 | if kp1 is None or len(kp1) < 10:
19 | print("特征点太少")
20 | return base_image, None
21 |
22 | bf = cv2.BFMatcher()
23 | matches = bf.knnMatch(des1, des2, k=2)
24 |
25 | good = []
26 | for m, n in matches:
27 | if m.distance < 0.75 * n.distance:
28 | good.append(m)
29 |
30 | print(f"匹配点数量: {len(good)}")
31 | if len(good) <= 4:
32 | print("匹配点太少")
33 | return base_image, None
34 |
35 | src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
36 | dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
37 |
38 | M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
39 |
40 | if M is None:
41 | return base_image, None
42 |
43 | h, w = gray_piece.shape[:2]
44 | pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2)
45 | dst = cv2.perspectiveTransform(pts, M)
46 | # 绘制匹配区域
47 | matched = base_image.copy()
48 | cv2.polylines(matched, [np.int32(dst)], True, (0, 255, 0), 3)
49 | # 在匹配图上展示使用的关键点
50 | for i, m in enumerate(good):
51 | # 获取原图中的关键点坐标
52 | x2, y2 = kp2[m.trainIdx].pt
53 | cv2.circle(matched, (int(x2), int(y2)), 5, (255, 0, 255), -1)
54 |
55 | angle = -np.arctan2(M[0, 1], M[0, 0]) * 180 / np.pi
56 | return matched, angle
57 |
--------------------------------------------------------------------------------
/src/main.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 |
4 | from camera import open_camera
5 | from detector.sift import match_with_sift
6 |
7 | global base_image, gray_base, masked_preview
8 | global last_processing_time
9 | global last_result
10 |
11 |
12 | def rotate_image(image, angle):
13 | height, width = image.shape[:2]
14 | center = (width // 2, height // 2)
15 |
16 | rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
17 | rotated = cv2.warpAffine(image, rotation_matrix, (width, height),
18 | flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT,
19 | borderValue=(255, 255, 255))
20 | return rotated
21 |
22 |
23 | def display(piece, mask, matched_result, angle):
24 | h_match, w_match = matched_result.shape[:2]
25 | left_ratio = 0.7
26 | total_width = int(w_match / left_ratio)
27 | left_width = int(total_width * left_ratio)
28 | right_width = total_width - left_width
29 |
30 | panel_height = h_match // 3
31 | total_height = h_match
32 |
33 | result = np.ones((total_height, total_width, 3), dtype=np.uint8) * 255
34 |
35 | left_height = total_height
36 | left_img = cv2.resize(matched_result, (left_width, left_height))
37 | result[0:left_height, 0:left_width] = left_img
38 |
39 | right_x = left_width
40 | piece_resized = cv2.resize(piece, (right_width, panel_height))
41 | result[0:panel_height, right_x:total_width] = piece_resized
42 |
43 | # 摄像头预览
44 | margin_ratio = 0.1 # 边距比例
45 | margin_h = int(panel_height * margin_ratio)
46 | margin_w = int(right_width * margin_ratio)
47 | cv2.rectangle(
48 | result,
49 | (right_x + margin_w, margin_h),
50 | (total_width - margin_w, panel_height - margin_h),
51 | (0, 255, 0), 2
52 | )
53 |
54 | # 掩膜处理后图像
55 | masked_piece = create_masked_piece(mask, piece)
56 | masked_resized = cv2.resize(masked_piece, (right_width, panel_height))
57 | result[panel_height:panel_height * 2, right_x:total_width] = masked_resized
58 |
59 | # 匹配成功时显示旋转图像
60 | if angle is not None:
61 | rotated_piece = rotate_image(piece, angle)
62 | rotated_resized = cv2.resize(rotated_piece, (right_width, panel_height))
63 | result[panel_height * 2:total_height, right_x:total_width] = rotated_resized
64 | angle_text = f"rotated: {angle:.1f}°"
65 | cv2.putText(
66 | result,
67 | angle_text,
68 | (right_x + 10, panel_height * 2 + 30),
69 | cv2.FONT_HERSHEY_SIMPLEX,
70 | 0.6, (0, 0, 0), 1
71 | )
72 | else:
73 | # 匹配失败时右下区域保持空白
74 | pass
75 | return result
76 |
77 |
78 | def callback_process_frame(piece, mask):
79 | matched_result, angle = match_with_sift(base_image, gray_base, piece, mask)
80 | result_display = display(piece, mask, matched_result, angle)
81 | cv2.imshow("jigsaw", result_display)
82 |
83 |
84 | def create_masked_piece(mask, piece):
85 | # 创建掩膜效果预览
86 | mask_3channel = cv2.merge([mask, mask, mask])
87 | mask_3channel = mask_3channel.astype(np.float32) / 255
88 | darkened = (piece * 0.3).astype(np.uint8)
89 | masked_area = (piece * mask_3channel).astype(np.uint8)
90 | # 使用掩膜合并
91 | masked_piece = darkened.copy()
92 | masked_piece = np.where(mask_3channel > 0, masked_area, masked_piece)
93 | # 添加掩膜边界线
94 | mask_outline = cv2.dilate(mask, np.ones((3, 3), np.uint8)) - mask
95 | mask_outline_idx = mask_outline > 0
96 | if np.any(mask_outline_idx):
97 | masked_piece[mask_outline_idx] = [0, 0, 255]
98 | return masked_piece
99 |
100 |
101 | def main():
102 | # 初始化全局变量
103 | global base_image, gray_base
104 | camera_index = 0
105 | crop_ratio = 0.4
106 | base_image = cv2.imread("../base.jpg")
107 | if base_image is None:
108 | print("错误:无法加载原始拼图图像")
109 | return
110 | # 计算原图的灰度图像
111 | gray_base = cv2.cvtColor(base_image, cv2.COLOR_BGR2GRAY)
112 |
113 | cv2.namedWindow("jigsaw", cv2.WINDOW_NORMAL)
114 | open_camera(camera_index, crop_ratio, callback_process_frame)
115 |
116 |
117 | if __name__ == "__main__":
118 | main()
119 |
--------------------------------------------------------------------------------