├── .gitignore ├── Arduino Programes └── Scanner.ino ├── LICENSE ├── README.md ├── Raspberry pi Programes └── scanner.py ├── TEST date &Show Programes ├── model.npy └── test.py └── 电路图.psd /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /Arduino Programes/Scanner.ino: -------------------------------------------------------------------------------- 1 | #include 2 | const int stepsPerRevolution = 3600; 3 | /*接线说明 4 | * 注意:由于所选继电器为固态交流继电器,所以在继电器状态变为关闭后, 5 | * 必须将输入端电位拉低后才能关闭继电器,但如果采用直流继电器则无需这么麻烦 6 | * 激光触发 3 7 | * 激光使能 4 8 | * 电机脉冲 9 9 | * 电机方向 11 10 | * 电机使能 10 11 | */ 12 | Stepper myStepper = Stepper(stepsPerRevolution, 8, 9);//引脚8,9为脉冲输出引脚 13 | String data = ""; //串口接收的数据 14 | //0,1引脚为串口引脚占用 15 | int switchLight=3;//激光触发 16 | int enableLight = 4; //激光控制引脚 17 | int enableStepper = 10; //电机使能引脚 18 | int directStepper = 11; //电机方向引脚 19 | int stepSpeed=40; 20 | 21 | void setup() { 22 | //引脚设置输出模式 23 | pinMode(switchLight, OUTPUT); 24 | pinMode(enableLight, OUTPUT); 25 | pinMode(enableStepper, OUTPUT); 26 | pinMode(directStepper, OUTPUT); 27 | //默认状态 28 | digitalWrite(switchLight, HIGH); 29 | digitalWrite(enableLight, LOW); 30 | digitalWrite(enableStepper, LOW); 31 | digitalWrite(directStepper, LOW); 32 | //设置步进电机步进距 33 | myStepper.setSpeed(stepSpeed); 34 | //初始化串口程序 35 | Serial.begin(9600);//设置串口波特率 36 | while (Serial.read() >= 0) {}; //清除串口缓存 37 | } 38 | 39 | void loop() { 40 | data = "";//接收数据置空 41 | if (Serial.available() > 0) { 42 | delay(5); 43 | //获取串口数据 44 | if (Serial.read() == '<') { 45 | data = Serial.readStringUntil('>'); 46 | } else { 47 | Serial.println("Data ERROR!!!"); 48 | } 49 | //Serial.println(data); 50 | } 51 | //打开激光 52 | if (!data.compareTo("lightON")) { 53 | Serial.println("1"); 54 | digitalWrite(switchLight, HIGH); 55 | digitalWrite(enableLight, HIGH); 56 | } 57 | //关闭激光 58 | if (!data.compareTo("lightOFF")) { 59 | Serial.println("1"); 60 | digitalWrite(switchLight, LOW); 61 | digitalWrite(enableLight, LOW); 62 | } 63 | //步进 64 | if (!data.compareTo("StepOne")) { 65 | Serial.println("1"); 66 | myStepper.step(2); 67 | } 68 | //旋转一周 69 | if (!data.compareTo("StepRun")) { 70 | Serial.println("1"); 71 | myStepper.setSpeed(40); 72 | for (int j = 0; j <= 6400; j++) { 73 | myStepper.step(1); 74 | } 75 | myStepper.setSpeed(stepSpeed); 76 | } 77 | //方向负 78 | if (!data.compareTo("directRight")) { 79 | Serial.println("1"); 80 | digitalWrite(directStepper, HIGH); 81 | } 82 | //方向正 83 | if (!data.compareTo("directLeft")) { 84 | Serial.println("1"); 85 | digitalWrite(directStepper, LOW); 86 | } 87 | //脱机 88 | if (!data.compareTo("StepOFF")) { 89 | Serial.println("1"); 90 | digitalWrite(enableStepper, HIGH); 91 | } 92 | //运行 93 | if (!data.compareTo("StepON")) { 94 | Serial.println("1"); 95 | digitalWrite(enableStepper, LOW); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Design-and-Implementation-of-Three-dimensional-Scanning-System-for-Structured-Light-Based-on-Raspber 2 | # 基于树莓派的结构光三维扫描仪设计与实现 3 | 4 | 本扫描仪程序分为两部分,一部分是树莓派上的Python程序,一部分是Arduino上的硬件程序。 5 | 树莓派上在部署程序之前,请依次配置好树莓派环境 6 | 树莓派操作系统:Raspbian 7 | 树莓派配置项: 8 | 1、树莓派的串口请设置为GPIO的形式 9 | 2、本程序基于Python3.5开发,请为树莓派配置好相应的语言环境。 10 | 3、请配置程序所依赖的库:OpenCV,Numpy。 11 | 配置方法不会请自行百度。 12 | 13 | 硬件接线参考 电路图.psd 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Raspberry pi Programes/scanner.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import time 3 | import cv2 4 | from picamera import PiCamera 5 | import numpy as np 6 | # from scipy import io 7 | import multiprocessing 8 | import math 9 | import threading 10 | 11 | 12 | # import matplotlib.pyplot as plt 13 | 14 | 15 | class MySerial: 16 | def __init__(self): 17 | self._ser = serial.Serial('/dev/ttyAMA0', 9600) # 初始化串口 18 | # 命令初始化 19 | self.STEP_CMD_ON = ''.encode('ascii') 20 | self.STEP_CMD_OFF = ''.encode('ascii') 21 | self.STEP_CMD_ONE_STEP = ''.encode('ascii') 22 | self.STEP_CMD_RUN_TEST = ''.encode('ascii') 23 | self.STEP_CMD_DIR_RIGHT = ''.encode('ascii') 24 | self.STEP_CMD_DIR_LEFT = ''.encode('ascii') 25 | self.LIGHT_CMD_ON = ''.encode('ascii') 26 | self.LIGHT_CMD_OFF = ''.encode('ascii') 27 | 28 | def write(self, cmd): 29 | ''' 30 | :param cmd: 待发送的命令 31 | :return: 32 | ''' 33 | try: 34 | self._ser.write(cmd) 35 | except KeyboardInterrupt as serialException: 36 | print(serialException) 37 | 38 | """ 39 | def write1(self, cmd): 40 | ''' 41 | :param cmd: 待发送的命令 42 | :return: 43 | ''' 44 | if not self.ser.isOpen(): 45 | self.ser.open() 46 | try: 47 | self.ser.write(cmd) 48 | except KeyboardInterrupt as serialException: 49 | print(serialException) 50 | """ 51 | 52 | def close(self): 53 | self._ser.close() 54 | 55 | def open(self): 56 | self._ser.open() 57 | 58 | 59 | class Stepper: 60 | ROUND = 1600 61 | 62 | def __init__(self): 63 | self._ser = MySerial() 64 | self.closeStep() 65 | self.rightRun() 66 | 67 | def openStep(self): 68 | self._ser.write(self._ser.STEP_CMD_ON) 69 | 70 | def closeStep(self): 71 | self._ser.write(self._ser.STEP_CMD_OFF) 72 | 73 | def rightRun(self): 74 | self._ser.write(self._ser.STEP_CMD_DIR_RIGHT) 75 | 76 | def leftRun(self): 77 | self._ser.write(self._ser.STEP_CMD_DIR_LEFT) 78 | 79 | def stepOne(self): 80 | self.openStep() 81 | self._ser.write(self._ser.STEP_CMD_ONE_STEP) 82 | 83 | def stepRound(self): 84 | self.openStep() 85 | self._ser.write(self._ser.STEP_CMD_RUN_TEST) 86 | self.closeStep() 87 | 88 | def angleRun(self, angle=360): 89 | ''' 90 | :param angle: 转动角度 91 | :return: 92 | ''' 93 | times = int((angle / 360) * self.ROUND) # 步进次数 94 | for t in range(times): 95 | self._ser.write(self._ser.STEP_CMD_ONE_STEP) 96 | 97 | 98 | class Light: 99 | def __init__(self): 100 | self._ser = MySerial() 101 | 102 | def openLight(self): 103 | self._ser.write(self._ser.LIGHT_CMD_ON) 104 | 105 | def closeLight(self): 106 | self._ser.write(self._ser.LIGHT_CMD_OFF) 107 | 108 | 109 | class MyCamera: 110 | def __init__(self): 111 | self.camera = PiCamera() # 初始化相机 112 | self.PHOTO_INFO = {'width': int(1920), 'height': int(1408), 'mode': 3} # 照片格式 113 | self.camera.resolution = (self.PHOTO_INFO['width'], self.PHOTO_INFO['height']) # 设置照片格式 114 | self.camera.start_preview() # 启动相机 115 | 116 | def openCamera(self): 117 | self.camera.start_preview() # 启动相机 118 | 119 | def getImage(self): 120 | ''' 121 | :return: 返回采集的照片 122 | ''' 123 | img = np.empty((self.PHOTO_INFO['height'] * self.PHOTO_INFO['width'] * self.PHOTO_INFO['mode'],), 124 | dtype=np.uint8) 125 | self.camera.capture(img, 'bgr') 126 | img = img.reshape((self.PHOTO_INFO['height'], self.PHOTO_INFO['width'], self.PHOTO_INFO['mode'])) 127 | return img 128 | 129 | def closeCamera(self): 130 | self.camera.close() 131 | 132 | 133 | class ImageHandle: 134 | def __init__(self): 135 | self._InterestRange = {'left_col': 720, 'top_row': 840, 'right_col': 940, 'bottom_row': 1270} # 参考范围 136 | sLine = self.findCenterLine( 137 | self.rangeByColors(self.getInterestRange(cv2.imread('standerd.png')))) # 参考直线 138 | 139 | def getImgSize(self): 140 | return self._InterestRange['bottom_row'] - self._InterestRange['top_row'], self._InterestRange['right_col'] - \ 141 | self._InterestRange['left_col'] 142 | 143 | def getGrayImg(self, img): 144 | img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 145 | return img 146 | 147 | def getOutLine(self, img): 148 | ''' 获取轮廓 ''' 149 | img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 150 | edges = cv2.Canny(img, 30, 90) 151 | return edges 152 | 153 | def getGaussianBlur(self, img): 154 | '''高斯模糊''' 155 | kernel_size = (5, 5) 156 | sigma = 2.0 157 | return cv2.GaussianBlur(img, kernel_size, sigma) 158 | 159 | def getLines(self, img): 160 | edges = cv2.Canny(img, 50, 200) 161 | minLineLength = 300 162 | maxLineGap = 15 163 | lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength, maxLineGap) 164 | for line in lines: 165 | for x1, y1, x2, y2 in line: 166 | cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) 167 | return img 168 | 169 | def getInterestRange(self, img): 170 | img = img[self._InterestRange['top_row']:self._InterestRange['bottom_row'], 171 | self._InterestRange['left_col']:self._InterestRange['right_col']] 172 | 173 | return img 174 | 175 | def rangeByColors(self, img, *colors): 176 | 177 | ''' 178 | 根据给定的颜色范围范围颜色范围图片 179 | :param img: 兴趣范围的图片 180 | :type colors: np.array,给定的任何颜色 181 | ''' 182 | # 生成颜色范围 183 | if len(colors) == 0: 184 | # 未给定颜色使用默认颜色范围 185 | lower_color = np.array([0, 0, 135]) 186 | upper_color = np.array([136, 150, 255]) 187 | else: 188 | lower_color = np.min(np.array(colors), axis=0) 189 | upper_color = np.max(np.array(colors), axis=0) 190 | mask = cv2.inRange(img, lower_color, upper_color) 191 | return mask 192 | 193 | def rangeByGray(self, img, *colors): 194 | 195 | ''' 196 | 根据灰度滤波图像 197 | :param img: 兴趣范围的图片 198 | :type colors: np.array,给定的二值颜色范围 199 | ''' 200 | # 生成颜色范围 201 | if len(colors) == 0: 202 | # 未给定颜色使用默认颜色范围 203 | lower_color = 100 204 | upper_color = 255 205 | else: 206 | lower_color = np.min(np.array(colors), axis=0) 207 | upper_color = np.max(np.array(colors), axis=0) 208 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 209 | mask = cv2.inRange(gray, lower_color, upper_color) 210 | return mask 211 | 212 | def findCenterLine(self, img): 213 | ''' 214 | :param img: 二值图片 215 | :return: 直线 216 | 无奈~~~时间太长了 217 | ''' 218 | # 根据给定图片生成空图片 219 | # start = time.time() 220 | lineImg = np.empty(img.shape, dtype=np.uint8) 221 | lineImg[:] = 0 222 | # 包含特征像素的行 223 | line_rows = [] 224 | rowP, colP = np.where(img == 255) 225 | [line_rows.append(i) for i in (rowP) if not i in line_rows] 226 | # 根据每行目标像素位置算出每行中心像素位置 227 | for row in line_rows: 228 | # 查询以获得一行中拥有目标像素的点的索引 229 | cols_index = np.where(rowP == row) 230 | # 目标点列的位置 231 | cols = [] 232 | col = None 233 | # 根据索引以获取目标的列位置 234 | cols.append((colP[cols_index])) 235 | # 计算每行的直线中心 236 | col = int(np.average(colP[cols_index])) 237 | lineImg[row][col] = 255 238 | # print('get rang time:' + str(time.time() - start)) 239 | return lineImg 240 | 241 | def getPosition(self, img, angle): 242 | ''' 243 | 标定参数:1cm为24个像素点 1920/2下(转台中心位置) 244 | 1cm为42个像素点 1920下 245 | 焦距:F = (P x D) / W 246 | P:41,D:42.1,W:1===>F:1880 247 | 每向前移动1cm,激光为止平移3个像素 1920/2下 248 | 每向前移动1cm,激光为止平移13个像素 1920下 249 | 摄像头距离转台中心为42.1cm 250 | ''' 251 | sLine = self.findCenterLine( 252 | self.rangeByColors(self.getInterestRange(cv2.imread('standerd.png')))) # 参考直线,建议该变量放到全局(读写操作费时间) 253 | # cv2.imshow('sl', sLine) 254 | # cv2.waitKey(0) 255 | interestImg = self.getInterestRange(img) 256 | blurImg = self.getGaussianBlur(interestImg) # 图片模糊处理 257 | mask1 = self.rangeByGray(blurImg) # 灰度滤波 258 | mask2 = self.rangeByColors(blurImg) # 阈值滤波 259 | laserLine = self.findCenterLine(mask1 | mask2) # 实际激光直线 260 | # cv2.imshow('ll', laserLine) 261 | # cv2.waitKey(0) 262 | sx, sy = np.where(sLine == 255) 263 | lx, ly = np.where(laserLine == 255) 264 | # sx = sx.tolist() 265 | lx = lx.tolist() 266 | # pointInfo = np.empty(img.shape) 267 | # print(type(lx)) 268 | lineInfo = np.empty([len(sx), 3]) 269 | lineInfo[:] = 0 270 | for sp in range(len(sx)): 271 | splot_y = sy[sp] 272 | if sp in lx: 273 | lplot_y = ly[lx.index(sp)] 274 | # print(sp, lplot_y - splot_y) 275 | pixDistence = lplot_y - splot_y 276 | # print(pixDistence) 277 | # if pixDistence > 0: 278 | # deepth_cam = 42.5 - (abs(pixDistence) * (1 / 13)) 279 | # else: 280 | # deepth_cam = 42.5 + abs(pixDistence) * (1 / 13) 281 | deepth = round(pixDistence * (1 / 13), 3) 282 | p_x = round(deepth * math.cos(angle), 3) 283 | p_y = round(deepth * math.sin(angle), 3) 284 | p_z = round((len(sx) - sp) * (1 / 15)) 285 | lineInfo[sp, 0] = p_x 286 | lineInfo[sp, 1] = p_y 287 | lineInfo[sp, 2] = p_z 288 | #print(lineInfo) 289 | return lineInfo 290 | # print('x:' + str(p_x) + '\ty:' + str(p_y) + '\tz:' + str(p_z)) 291 | 292 | 293 | class Scanner: 294 | 295 | # PIX_LENGTH = 100 / 24 # 像素长度,单位毫米 296 | 297 | def __init__(self): 298 | self._stepper = Stepper() 299 | self._light = Light() 300 | self._camera = MyCamera() 301 | self._imageHandle = ImageHandle() 302 | self._stepper.openStep() # 电机使能 303 | self._light.closeLight() # 关闭激光 304 | time.sleep(1) # 等待设备时间 305 | self.model = None # np.empty([0]) # 创建空模型 306 | 307 | def scan(self, angle): 308 | times = int((angle / 360) * self._stepper.ROUND) # 根据角度计算出转动的次数 309 | # print(times) # 测试 310 | self._stepper.openStep() # 电机使能 311 | self._stepper.rightRun() # 设置转动方向 312 | for t in range(times): 313 | # color_img = self._camera.getImage() # 采集颜色图像 314 | # cv2.imwrite('color.jpg', color_img) # 保存颜色图片 315 | self._light.openLight() 316 | laser_img = self._camera.getImage() # 采集激光图像 317 | self._light.closeLight() 318 | start = time.time() 319 | print(t) 320 | lineInfo = self._imageHandle.getPosition(img=laser_img, angle=(math.pi) * (t * angle / self._stepper.ROUND)) 321 | for l in lineInfo: 322 | print(l) 323 | if self.model is None: 324 | self.model = lineInfo 325 | else: 326 | self.model = np.append(self.model, lineInfo, axis=0) 327 | print(self.model.shape) 328 | print(time.time() - start) 329 | scanner.saveAsFile('model', scanner.model) 330 | print("-----------------Next Time-----------------") 331 | 332 | self._stepper.stepOne() # 步进 333 | 334 | def saveAsFile(self, filename, file): 335 | # io.savemat(filename + ".mat", {'array': file}) 336 | np.save(filename, file) 337 | 338 | def closeScanner(self): 339 | self._stepper.closeStep() 340 | self._light.closeLight() 341 | # self.saveAsFile('model', self.model) 342 | 343 | 344 | if __name__ == '__main__': 345 | pool = multiprocessing.Pool(processes=4) 346 | scanner = Scanner() 347 | try: 348 | # scanner.scan(20) 349 | pool.apply_async(scanner.scan(360), (1,)) 350 | finally: 351 | scanner.closeScanner() 352 | # scanner.saveAsFile('model', scanner.model) 353 | -------------------------------------------------------------------------------- /TEST date &Show Programes/model.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EulerBlind/3D-Scanning-Based-on-Raspberry-pi-3/f6059a655c5d2f03464ef865df4d2146714a6714/TEST date &Show Programes/model.npy -------------------------------------------------------------------------------- /TEST date &Show Programes/test.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | from mpl_toolkits.mplot3d import Axes3D 4 | 5 | data = np.load('model.npy') 6 | ax = plt.subplot(111, projection="3d") 7 | # ax = plt.figure().add_subplot(111, projection="3d") 8 | 9 | 10 | ax.set_zlabel('Z') # 坐标轴 11 | ax.set_ylabel('Y') 12 | ax.set_xlabel('X') 13 | for d in data: 14 | x, y, z = d[0], d[1], d[2] 15 | ax.scatter(x, y, z, c="b") 16 | plt.show() -------------------------------------------------------------------------------- /电路图.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EulerBlind/3D-Scanning-Based-on-Raspberry-pi-3/f6059a655c5d2f03464ef865df4d2146714a6714/电路图.psd --------------------------------------------------------------------------------