Commit a9e32be9 authored by Wan Xia's avatar Wan Xia
Browse files

first update

parent 9171d3c8
No related merge requests found
Pipeline #9946 canceled with stages
Showing with 2287 additions and 90 deletions
+2287 -90
# 机器人端
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://222.71.182.250:1080/pb/vi/robot.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://222.71.182.250:1080/pb/vi/robot/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
`pip3 install opencv-python==4.5.5.64`
\ No newline at end of file
Description = cam0 Service
After = multi-user.target
[Service]
ExecStart = /usr/bin/python3 /home/sage/deploy/ocr_server/photo_cap_server_0.py
WorkingDirectory = /home/sage/deploy/ocr_server
User = sage
[Install]
WantedBy=multi-user.target
\ No newline at end of file
Description = cam2 Service
After = multi-user.target
[Service]
ExecStart = /usr/bin/python3 /home/sage/deploy/ocr_server/photo_cap_server_2.py
WorkingDirectory = /home/sage/deploy/ocr_server
User = sage
[Install]
WantedBy=multi-user.target
\ No newline at end of file
Description = cam4 Service
After = multi-user.target
[Service]
ExecStart = /usr/bin/python3 /home/sage/deploy/ocr_server/photo_cap_server_4.py
WorkingDirectory = /home/sage/deploy/ocr_server
User = sage
[Install]
WantedBy=multi-user.target
\ No newline at end of file
Description = cam6 Service
After = multi-user.target
[Service]
ExecStart = /usr/bin/python3 /home/sage/deploy/ocr_server/photo_cap_server_6.py
WorkingDirectory = /home/sage/deploy/ocr_server
User = sage
[Install]
WantedBy=multi-user.target
\ No newline at end of file
cam_search.py 0 → 100644
import cv2
from multiprocessing import Process
def show_img(cam_id):
print(f'cam{cam_id} start')
cap = cv2.VideoCapture(cam_id)
cv2.namedWindow(f'img_{cam_id}', cv2.WINDOW_NORMAL)
while True:
_, f = cap.read()
cv2.imshow(f'img_{cam_id}', f)
if cv2.waitKey(1) == 27:
break
cap.release()
cv2.destroyWindow(f'img_{cam_id}')
if __name__ == '__main__':
cam_id_list = []
p_list = []
for i in range(20):
try:
cap = cv2.VideoCapture(i)
if cap.isOpened():
print(f'cam{i:>2} is opened')
cam_id_list.append(i)
else:
print(f'cam{i:>2} is close')
except Exception as e:
print(f'open cam{i:>2}, {e}')
finally:
try:
cap.release()
except Exception as e:
pass
for i in cam_id_list:
p = Process(target=show_img, args=(i,), daemon=True)
p.start()
p_list.append(p)
for j in p_list:
j.join()
Description = OCR Local Service
After = multi-user.target
[Service]
ExecStart = /usr/bin/python3 /home/sage/deploy/ocr_server/ocr_server_local.py
WorkingDirectory = /home/sage/deploy/ocr_server
User = sage
[Install]
WantedBy=multi-user.target
{
"rtsp": "rtsp://{}:554/user=admin&password=&channel=1&stream=0.sdp?",
"ocr_post_address": "http://127.0.0.1:8740/visual",
"camera_ip_set": [
"192.168.188.64",
"192.168.188.65",
"192.168.188.66",
"192.168.188.67"
],
"cam_id": "0264",
"cam_exp":"75",
"web_enable": "0000",
"remote_host": "172.16.3.221",
"port": "21",
"username": "sage",
"psw": "sagetech",
"target_path": "images",
"remote_path": "images",
"multi-thread(upload)": "8",
"image_num_per_level": "6",
"days": "7",
"sleep(min)": "1",
"log_path": "logs"
}
\ No newline at end of file
import copy
import ctypes
import json
import os
import queue
import time
from multiprocessing import Manager
from threading import Thread
from flask import Flask
from ocr_utils import upload_image, monitor_overdue, set_log, get_stime, post_res, my_print, upload_task
from socket import socket, AF_INET, SOCK_STREAM
from collections import Counter, defaultdict
app = Flask(__name__)
app.debug = False
my_print('ocr_server_local start')
@app.route('/')
def hello_world():
return 'Hello World'
@app.route('/over')
def over():
global timestamp
global upload_task_q
global level_dict
upload_task_q.put((timestamp, level_dict))
my_print(f'timestamp={timestamp}, level_dict={level_dict} is over', 'MAIN_SERVER_OVER')
return '1'
# 重置所有变量
@app.route('/reset')
def reset():
my_print('reset receive')
global shelfID
global shelf_dict
global level_list
global level_dict # {'shelf1':[['1','2','5','6'],['2','3','4','5']],'shelf2':[['1','2','5','6'],['2','3','4','5']]}
global timestamp
global upload_task_q
try:
shelfID = None
shelf_dict = Counter()
level_list = []
level_dict = defaultdict(list)
timestamp = get_stime()
task_id_shm.value = timestamp
try:
while not upload_task_q.empty():
upload_task_q.get()
except Exception as e:
pass
my_print('reset done!', 'MAIN_SERVER_RESET')
return '1'
except Exception as e:
my_print(f'reset error, {e}', 'MAIN_SERVER_RESET_ERROR')
return '0'
# 设定书架,如与上一次相同则跳过,否则更新书架出现的次数,以及书架对应的当前层
@app.route('/start/<string:shelf>')
def start(shelf):
my_print(f'start shelf=[{shelf}] receive', 'MAIN_SERVER_START')
global shelfID
global shelf_dict
global level_list
if shelfID is not None and shelfID == shelf:
return '1'
shelfID = shelf
if shelfID is None or shelfID == 'None':
my_print(f'shelfID cannot be None', 'MAIN_SERVER_START')
return '0'
shelf_dict[shelfID] += 1
if len(level_dict[shelfID]) < 2:
level_dict[shelfID].append(copy.deepcopy(level_list))
my_print(f'level_dict[shelfID]={level_dict[shelfID]} append level_list={level_list}', 'MAIN_SERVER_START')
else:
level_dict[shelfID] = [copy.deepcopy(level_list)]
my_print(f'set level_dict[shelfID]={level_dict[shelfID]} is [{level_list}]', 'MAIN_SERVER_START')
my_print(f'set timestamp={timestamp}, shelfID={shelfID}, shelf_dict={shelf_dict}, level_dict={level_dict}!',
'MAIN_SERVER_START')
return '1'
# 设定当前扫描的层序号
@app.route('/level/<string:levels>')
def set_level(levels):
my_print(f'set level [{levels}] receive', 'MAIN_SERVER_LEVEL')
global level_list
try:
level_list = levels.split(',')
if not level_list:
my_print(f'levels cannot be null', 'MAIN_SERVER_LEVEL_ERROR')
return '0'
if len(set(level_list)) != len(level_list):
my_print(f'level_list={level_list} cannot contain duplicate levelID', 'MAIN_SERVER_LEVEL_ERROR')
return '0'
my_print(f'set level done!', 'MAIN_SERVER_LEVEL')
return '1'
except Exception as e:
my_print(f'set level error,{e}', 'MAIN_SERVER_LEVEL_ERROR')
return '0'
# 给相机服务下达拍照指令
@app.route('/cap/<string:img_name>')
def get_cam(img_name):
my_print(f'cap [{img_name}] receive')
global shelfID
global shelf_dict
global level_list
global level_dict
global timestamp
if isinstance(timestamp, str):
task_path = os.path.join(target_path, timestamp)
else:
my_print(f'timestamp={timestamp} is not string', 'MAIN_SERVER_CAP_ERROR')
return '0'
if not os.path.exists(task_path):
os.mkdir(task_path)
if isinstance(shelfID, str) and shelfID != 'None':
shelf_path = os.path.join(task_path, shelfID)
else:
my_print(f'shelfID={shelfID} is not string or cannot be None', 'MAIN_SERVER_CAP_ERROR')
return '0'
if not os.path.exists(shelf_path):
os.mkdir(shelf_path)
my_print(f'caped image will be saved in shelf_path={shelf_path}', 'MAIN_SERVER_CAP')
skip_level = []
try:
if shelf_dict[shelfID] % 2 == 0:
if len(level_dict[shelfID]) != 2:
my_print(f'existed len of level_list do not match the shelfID counter', 'MAIN_SERVER_CAP_ERROR')
return '0'
previous_levels = level_dict[shelfID][0]
now_levels = level_dict[shelfID][-1]
for level in now_levels:
if level in previous_levels:
skip_level.append(level)
my_print(f'previous_levels={previous_levels}, now_levels={now_levels}, skip_level={skip_level}',
'MAIN_SERVER_CAP')
my_print(f'current level_list={level_list}', 'MAIN_SERVER_CAP')
for i, level_id in enumerate(level_list):
if level_id in skip_level:
continue
level_path = os.path.join(shelf_path, level_id)
my_print(f'i={i}, current level_path={level_path}', 'MAIN_SERVER_CAP')
if not os.path.exists(level_path):
os.mkdir(level_path)
if not os.path.exists(f'{level_path}/.post'):
with open(f'{level_path}/.post', 'wt') as f:
f.write('0')
cam_idx = level2cam[i]
my_print(f'i={i}, send cap msg to cam_idx={cam_idx}', 'MAIN_SERVER_CAP')
camID_sockets[cam_idx].send(
('||'.join([str(cam_idx), target_path, timestamp, shelfID, level_id, img_name])).encode())
my_print(f'send cap done!', 'MAIN_SERVER_CAP')
return '1'
except Exception as e:
my_print(f'send cap error, {e}', 'MAIN_SERVER_CAP_ERROR')
return '0'
if __name__ == '__main__':
manager = Manager()
conf_path = 'ocr_local_config.json'
conf = open(conf_path, 'r')
param_dict = json.load(conf)
conf.close()
log_path = param_dict['log_path']
set_log(log_path, get_stime(), True)
remote_host = param_dict['remote_host'] # 各项参数见文档站说明
ocr_post_address = param_dict['ocr_post_address'] # 各项参数见文档站说明
port = int(param_dict['port'])
username = param_dict['username']
psw = param_dict['psw']
target_path = param_dict['target_path']
remote_path = param_dict['remote_path']
upload_max = int(param_dict['multi-thread(upload)'])
days = int(param_dict['days'])
sleep_time = float(param_dict['sleep(min)'])
level2cam = [int(cam_id) for cam_id in param_dict['cam_id']]
if not os.path.exists(target_path):
os.mkdir(target_path)
camID_sockets = {}
time.sleep(5)
for camId in level2cam: # 绑定相机tcp服务端口至相机端口号
tmp_socket = socket(AF_INET, SOCK_STREAM)
retry_cnt = 0
while True:
my_print(f'try to connect cam{camId} server', 'MAIN_SERVER')
try:
tmp_socket.connect(('localhost', 20010 + camId))
my_print(f'connect cam{camId} server successful', 'MAIN_SERVER')
break
except Exception as e:
my_print(f'connect cam{camId} server error, {e}', 'MAIN_SERVER_ERROR')
pass
time.sleep(5)
retry_cnt += 1
if retry_cnt > 3:
break
camID_sockets[camId] = tmp_socket
time.sleep(1)
shelfID = None
timestamp = '19700101000000'
task_id_shm = manager.Value(ctypes.c_char_p, timestamp)
upload_task_q = queue.Queue()
shelf_dict = Counter()
level_list = []
level_dict = defaultdict(list)
Thread(target=upload_image,
args=(remote_host, port, username, psw, target_path, remote_path, upload_max,), daemon=True).start()
Thread(target=monitor_overdue, args=(target_path, days, sleep_time,), daemon=True).start()
Thread(target=post_res, args=(remote_host, target_path, ocr_post_address, task_id_shm,), daemon=True).start()
Thread(target=upload_task, args=(upload_task_q, target_path, ocr_post_address,), daemon=True).start()
app.run(host='127.0.0.1', port=8772)
ocr_utils.py 0 → 100644
+ 1439
0
View file @ a9e32be9
This diff is collapsed.
open_cam.py 0 → 100644
import cv2
cam_id = 0
cap = cv2.VideoCapture(cam_id, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)
cap.set(cv2.CAP_PROP_EXPOSURE, 300)
print(f'EXPOSURE:{cap.get(cv2.CAP_PROP_EXPOSURE)}')
flag = cap.isOpened()
print(f'open_flag:{flag}')
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
if flag:
while True:
ret, f = cap.read()
cv2.imshow('img', f)
last_key = cv2.waitKey(1)
if last_key == 27:
break
elif last_key == 32:
cv2.imwrite('test.png', f)
cap.release()
cv2.destroyAllWindows()
import glob
import json
import os
import pickle
import sys
from socketserver import BaseRequestHandler, TCPServer
import cv2
from ocr_utils import cap_usb_cam, cap_web_cam, my_print
cam_index = 0
if os.path.exists(f'cam{cam_index}.log'):
os.remove(f'cam{cam_index}.log')
class Logger(object):
def __init__(self, filename, stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.terminal.flush()
self.log.write(message)
self.log.flush()
def flush(self):
pass
sys.stdout = Logger(f'cam{cam_index}.log', sys.stdout)
sys.stderr = Logger(f'cam{cam_index}.log', sys.stderr)
my_print(f'cam{cam_index} start')
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
while True:
msg = self.request.recv(8192)
if not msg:
break
my_print(f'cam {cam_index} received msg={msg}')
cam_id, target_path, task_id, shelfID, level, img_name = str(msg)[2:-1].split('||')
img = next(cr) # 获取相机最新帧
if img is not None:
img_size = (img.shape[1], img.shape[0])
if wide_flag:
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, img_size, 0, img_size)
img = cv2.undistort(img, mtx, dist, None, newcameramtx)
level_path = f'{target_path}/{task_id}/{shelfID}/{level}'
img_file = '.'.join([img_name, '0', 'png'])
if not glob.glob(f'{level_path}/{img_name}.*.png'):
cv2.imwrite(f'{level_path}/{img_file}', img)
my_print(f'cam{cam_id} done')
self.request.send(f'cam{cam_id} done'.encode())
else:
my_print(f'img is None', 'ERROR')
self.request.send(f'cam{cam_id} cap fail'.encode())
if __name__ == '__main__':
buffsize = 1
wide_file = f'wide_dist_pickle_{cam_index}.p'
wide_flag = False
if os.path.exists(wide_file):
f = open(wide_file, 'rb')
dist_p = pickle.load(f, )
f.close()
mtx = dist_p['mtx']
dist = dist_p['dist']
wide_flag = True
conf_path = 'ocr_local_config.json'
conf = open(conf_path, 'r')
param_dict = json.load(conf)
conf.close()
cam_ind = param_dict['cam_id'].index(str(cam_index))
if int(param_dict['web_enable'][cam_ind]) == 0:
cam_exp = int(param_dict['cam_exp'])
cr = cap_usb_cam(cam_index, buffsize, cam_exp)
else:
cam_ip = param_dict['camera_ip_set'][cam_ind]
cr = cap_web_cam(param_dict['rtsp'].format(cam_ip), buffsize)
i = buffsize + 2
frame = None
while i > 0:
next(cr)
i -= 1
frame = next(cr)
if frame is None:
my_print(f'cannot open cam {cam_index}', 'ERROR')
serv = TCPServer(('', 20010 + cam_index), EchoHandler) # 开启一个TCP服务器
serv.serve_forever()
import glob
import json
import os
import pickle
import sys
from socketserver import BaseRequestHandler, TCPServer
import cv2
from ocr_utils import cap_usb_cam, cap_web_cam, my_print
cam_index = 2
if os.path.exists(f'cam{cam_index}.log'):
os.remove(f'cam{cam_index}.log')
class Logger(object):
def __init__(self, filename, stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.terminal.flush()
self.log.write(message)
self.log.flush()
def flush(self):
pass
sys.stdout = Logger(f'cam{cam_index}.log', sys.stdout)
sys.stderr = Logger(f'cam{cam_index}.log', sys.stderr)
my_print(f'cam{cam_index} start')
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
while True:
msg = self.request.recv(8192)
if not msg:
break
my_print(f'cam {cam_index} received msg={msg}')
cam_id, target_path, task_id, shelfID, level, img_name = str(msg)[2:-1].split('||')
img = next(cr) # 获取相机最新帧
if img is not None:
img_size = (img.shape[1], img.shape[0])
if wide_flag:
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, img_size, 0, img_size)
img = cv2.undistort(img, mtx, dist, None, newcameramtx)
level_path = f'{target_path}/{task_id}/{shelfID}/{level}'
img_file = '.'.join([img_name, '0', 'png'])
if not glob.glob(f'{level_path}/{img_name}.*.png'):
cv2.imwrite(f'{level_path}/{img_file}', img)
my_print(f'cam{cam_id} done')
self.request.send(f'cam{cam_id} done'.encode())
else:
my_print(f'img is None', 'ERROR')
self.request.send(f'cam{cam_id} cap fail'.encode())
if __name__ == '__main__':
buffsize = 1
wide_file = f'wide_dist_pickle_{cam_index}.p'
wide_flag = False
if os.path.exists(wide_file):
f = open(wide_file, 'rb')
dist_p = pickle.load(f, )
f.close()
mtx = dist_p['mtx']
dist = dist_p['dist']
wide_flag = True
conf_path = 'ocr_local_config.json'
conf = open(conf_path, 'r')
param_dict = json.load(conf)
conf.close()
cam_ind = param_dict['cam_id'].index(str(cam_index))
if int(param_dict['web_enable'][cam_ind]) == 0:
cam_exp = int(param_dict['cam_exp'])
cr = cap_usb_cam(cam_index, buffsize, cam_exp)
else:
cam_ip = param_dict['camera_ip_set'][cam_ind]
cr = cap_web_cam(param_dict['rtsp'].format(cam_ip), buffsize)
i = buffsize + 2
frame = None
while i > 0:
next(cr)
i -= 1
frame = next(cr)
if frame is None:
my_print(f'cannot open cam {cam_index}', 'ERROR')
serv = TCPServer(('', 20010 + cam_index), EchoHandler) # 开启一个TCP服务器
serv.serve_forever()
import glob
import json
import os
import pickle
import sys
from socketserver import BaseRequestHandler, TCPServer
import cv2
from ocr_utils import cap_usb_cam, cap_web_cam, my_print
cam_index = 4
if os.path.exists(f'cam{cam_index}.log'):
os.remove(f'cam{cam_index}.log')
class Logger(object):
def __init__(self, filename, stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.terminal.flush()
self.log.write(message)
self.log.flush()
def flush(self):
pass
sys.stdout = Logger(f'cam{cam_index}.log', sys.stdout)
sys.stderr = Logger(f'cam{cam_index}.log', sys.stderr)
my_print(f'cam{cam_index} start')
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
while True:
msg = self.request.recv(8192)
if not msg:
break
my_print(f'cam {cam_index} received msg={msg}')
cam_id, target_path, task_id, shelfID, level, img_name = str(msg)[2:-1].split('||')
img = next(cr) # 获取相机最新帧
if img is not None:
img_size = (img.shape[1], img.shape[0])
if wide_flag:
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, img_size, 0, img_size)
img = cv2.undistort(img, mtx, dist, None, newcameramtx)
level_path = f'{target_path}/{task_id}/{shelfID}/{level}'
img_file = '.'.join([img_name, '0', 'png'])
if not glob.glob(f'{level_path}/{img_name}.*.png'):
cv2.imwrite(f'{level_path}/{img_file}', img)
my_print(f'cam{cam_id} done')
self.request.send(f'cam{cam_id} done'.encode())
else:
my_print(f'img is None', 'ERROR')
self.request.send(f'cam{cam_id} cap fail'.encode())
if __name__ == '__main__':
buffsize = 1
wide_file = f'wide_dist_pickle_{cam_index}.p'
wide_flag = False
if os.path.exists(wide_file):
f = open(wide_file, 'rb')
dist_p = pickle.load(f, )
f.close()
mtx = dist_p['mtx']
dist = dist_p['dist']
wide_flag = True
conf_path = 'ocr_local_config.json'
conf = open(conf_path, 'r')
param_dict = json.load(conf)
conf.close()
cam_ind = param_dict['cam_id'].index(str(cam_index))
if int(param_dict['web_enable'][cam_ind]) == 0:
cam_exp = int(param_dict['cam_exp'])
cr = cap_usb_cam(cam_index, buffsize, cam_exp)
else:
cam_ip = param_dict['camera_ip_set'][cam_ind]
cr = cap_web_cam(param_dict['rtsp'].format(cam_ip), buffsize)
i = buffsize + 2
frame = None
while i > 0:
next(cr)
i -= 1
frame = next(cr)
if frame is None:
my_print(f'cannot open cam {cam_index}', 'ERROR')
serv = TCPServer(('', 20010 + cam_index), EchoHandler) # 开启一个TCP服务器
serv.serve_forever()
import glob
import json
import os
import pickle
import sys
from socketserver import BaseRequestHandler, TCPServer
import cv2
from ocr_utils import cap_usb_cam, cap_web_cam, my_print
cam_index = 6
if os.path.exists(f'cam{cam_index}.log'):
os.remove(f'cam{cam_index}.log')
class Logger(object):
def __init__(self, filename, stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.terminal.flush()
self.log.write(message)
self.log.flush()
def flush(self):
pass
sys.stdout = Logger(f'cam{cam_index}.log', sys.stdout)
sys.stderr = Logger(f'cam{cam_index}.log', sys.stderr)
my_print(f'cam{cam_index} start')
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
while True:
msg = self.request.recv(8192)
if not msg:
break
my_print(f'cam {cam_index} received msg={msg}')
cam_id, target_path, task_id, shelfID, level, img_name = str(msg)[2:-1].split('||')
img = next(cr) # 获取相机最新帧
if img is not None:
img_size = (img.shape[1], img.shape[0])
if wide_flag:
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, img_size, 0, img_size)
img = cv2.undistort(img, mtx, dist, None, newcameramtx)
level_path = f'{target_path}/{task_id}/{shelfID}/{level}'
img_file = '.'.join([img_name, '0', 'png'])
if not glob.glob(f'{level_path}/{img_name}.*.png'):
cv2.imwrite(f'{level_path}/{img_file}', img)
my_print(f'cam{cam_id} done')
self.request.send(f'cam{cam_id} done'.encode())
else:
my_print(f'img is None', 'ERROR')
self.request.send(f'cam{cam_id} cap fail'.encode())
if __name__ == '__main__':
buffsize = 1
wide_file = f'wide_dist_pickle_{cam_index}.p'
wide_flag = False
if os.path.exists(wide_file):
f = open(wide_file, 'rb')
dist_p = pickle.load(f, )
f.close()
mtx = dist_p['mtx']
dist = dist_p['dist']
wide_flag = True
conf_path = 'ocr_local_config.json'
conf = open(conf_path, 'r')
param_dict = json.load(conf)
conf.close()
cam_ind = param_dict['cam_id'].index(str(cam_index))
if int(param_dict['web_enable'][cam_ind]) == 0:
cam_exp = int(param_dict['cam_exp'])
cr = cap_usb_cam(cam_index, buffsize, cam_exp)
else:
cam_ip = param_dict['camera_ip_set'][cam_ind]
cr = cap_web_cam(param_dict['rtsp'].format(cam_ip), buffsize)
i = buffsize + 2
frame = None
while i > 0:
next(cr)
i -= 1
frame = next(cr)
if frame is None:
my_print(f'cannot open cam {cam_index}', 'ERROR')
serv = TCPServer(('', 20010 + cam_index), EchoHandler) # 开启一个TCP服务器
serv.serve_forever()
import glob
import os.path
for img_path in glob.glob('images/*/*/*/.posted'):
level_path, img_name = os.path.split(img_path)
os.rename(img_path, os.path.join(level_path, '.post'))
print('done')
import os
import time
for i in range(4):
index = i * 2
file_name = f'cam{index}.service'
password = 'sagetech'
replace = False
if os.path.exists(f'/etc/systemd/system/{file_name}'):
try:
cmd = f'systemctl restart {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
print(f'restart old {file_name}')
replace = True
except Exception as e:
print('restart error, ', e)
if not replace:
file_path = os.path.abspath(f'photo_cap_server_{index}.py')
WorkingDirectory = os.path.abspath('')
with open(f'{file_name}', 'w') as f:
f.writelines(
[
f'Description = Cam{index} Service\n',
'After = multi-user.target\n',
'[Service]\n',
f'ExecStart = /usr/bin/python3 {file_path}\n',
f'WorkingDirectory = {WorkingDirectory}\n',
'User = sage\n',
'[Install]\n',
'WantedBy=multi-user.target'
]
)
time.sleep(1)
cmd = f'cp {file_name} /etc/systemd/system/{file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl enable {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl start {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl status {file_name}'
res = os.system(f'echo "{password}" | sudo -S {cmd}')
print(f'{file_name}====>\n{res}')
time.sleep(1)
print('done')
import os
import time
file_name = f'ocr_local.service'
password = 'sagetech'
replace = False
if os.path.exists(f'/etc/systemd/system/{file_name}'):
try:
cmd = f'systemctl restart {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
print(f'restart old {file_name}')
replace = True
except Exception as e:
print('restart error, ', e)
if not replace:
file_path = os.path.abspath('ocr_server_local.py')
WorkingDirectory = os.path.abspath('')
with open(f'{file_name}', 'w') as f:
f.writelines(
[
f'Description = Ocr Local Service\n',
'After = multi-user.target\n',
'[Service]\n',
f'ExecStart = /usr/bin/python3 {file_path}\n',
f'WorkingDirectory = {WorkingDirectory}\n',
'User = sage\n',
'[Install]\n',
'WantedBy=multi-user.target'
]
)
time.sleep(1)
cmd = f'cp {file_name} /etc/systemd/system/{file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl enable {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl start {file_name}'
os.system(f'echo "{password}" | sudo -S {cmd}')
time.sleep(1)
cmd = f'systemctl status {file_name}'
res = os.system(f'echo "{password}" | sudo -S {cmd}')
print(f'{file_name}====>\n{res}')
time.sleep(1)
print('done')
setup.py 0 → 100644
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
extensions = [Extension("ocr_utils", # 文件名
["ocr_utils.py"], # 需要转换编译的python代码
# library_dirs=['/usr/lib/A','/usr/lib/B'], # C/C++库文件搜索文件夹
# libraries=['a.so','b.so'], # C/C++库文件名
include_dirs=["/usr/include/python3.8"] # 头文件python.h位置
)]
setup(ext_modules=cythonize(extensions, language_level=3)) # 3表示使用python3
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment