相机为basler,logic
balser相机识别条码,进行拍照
args[0] 为logging的参数保证log实时传输到GUI界面
调用方法:
main_process(args[0]).camera_run()
import sys
import errno
import cv2
import numpy as np
import json
import logging
import threading
import logging.handlers
from datetime import datetime
import subprocess
DEBUG = False
# 條碼解析庫
if not DEBUG:
from dbr import *
from pyzbar import pyzbar
# basler相機
from pypylon import pylon
sys.path.append('../')
# 刷槍串口通訊
import serial # 导入串口通信库
from time import sleep
ser = serial.Serial()
# define config variable
config = {}
# 获取当前日期
testdate = datetime.now().strftime('%Y%m%d')
class main_process:
flag = True
def __init__(self, loger):
self.logging = loger
# 读取治具编号
if not os.path.exists(r'D:\LabelAOI\Config\FIXID.INI'):
print('FIXID INI FILE NOT EXIST')
sys.exit(255)
self.fixid = self.Readfile(r'D:\LabelAOI\Config\FIXID.INI')
# 读取jason配置档
if DEBUG:
cfg_path = 'BOXAOI.json'
else:
cfg_path = 'D:\\LabelAOI\\Config\\BOXAOI_baslor.json'
self.config = main_process.ReadConfig(cfg_path)
self.outpath = self.config[self.fixid]['out_path']
webcams = self.config[self.fixid]['webcam']
# 扫码相机
self.scancams = [s for s in webcams if s.startswith('S') and s != 'S_main']
# scancams=[s for s in webcams if s.startswith('S')]
# 拍照相机
self.capcams = [s for s in webcams if s.startswith('L')]
# 主相机以外的相机
self.subcams = [s for s in webcams if s != 'S_main']
# log初始化
# self.InitLog(outpath=self.outpath)
# 导入jason config配置档
# logging = self.logging
@staticmethod
def ReadConfig(cfg_name):
with open(cfg_name, "r") as reader:
cfg = json.loads(reader.read())
return cfg
# 初始化log
# def InitLog(self, outpath='', level=logging.DEBUG):
# """ Generate log file
#
# Keyword Arguments:
# folder {str} -- log of folder (default: logs)
# file {str} -- log name (default: filename + .log)
# level object -- log level setup
#
# Returns:
# True -- Generate logging successful
# """
# # log 输出
# LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
# DATE_FORMAT = "%Y/%m/%d %H:%M:%S %p"
# formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT)
# if DEBUG:
# log_path = 'capture.log'
# else:
# log_path = os.path.join(outpath, 'capture.log')
# fh = logging.handlers.RotatingFileHandler(log_path,
# maxBytes=20 * 1024 * 1024, # Maximum file size 20MB,
# backupCount=20,
# encoding="utf-8") # added support UTF-8
# fh.setFormatter(formatter)
# fh.setLevel(logging.DEBUG)
# logging.basicConfig(format=LOG_FORMAT, datefmt=DATE_FORMAT, level=logging.DEBUG)
# logging.getLogger('').addHandler(fh) # '' is root logger name
# logging.getLogger('').setLevel(logging.DEBUG)
# print("InitLog() function execute successful.")
# print("")
# return True
# 判断字串由字母和数字组成
@staticmethod
def strtype_check(teststr):
checkstrs = str(teststr)
for chkstr in checkstrs:
if chkstr.isupper() or chkstr.islower() or chkstr.isdigit():
continue
else:
return False
return True
# 导入配置档
def Readfile(self, file):
with open(file, "r") as f:
content = f.readlines()
content1 = content[0].strip('\n')
return content1
@staticmethod
def getintcount(teststr):
intcount = 0
for i in teststr:
if i.isdigit():
intcount += 1
return intcount
# 图片裁剪
def cutimg(self, test_pic, testfun):
cuth, cutw, cutno = self.config[self.fixid][testfun][4:7]
img = cv2.imread(test_pic)
H, W, A = img.shape # 获取图片信息,高和宽
cut_h = int(cuth) # 高裁剪2
cut_w = int(cutw) # 宽裁剪2
cut_no = int(cutno) # 取裁剪3
a = H // cut_h
b = W // cut_w
count = 0
for i in range(0, H, a):
for j in range(0, W, b):
count += 1
if cut_no != None and count != cut_no:
continue
result = img[i:i + a, j:j + b]
savename = os.path.splitext(test_pic)[0] + "_cut_" + "%d.jpg" % count
cv2.imwrite(savename, result)
return savename
# 同步时间
@staticmethod
def synctime(testdate):
year = int(testdate[:4])
month = int(testdate[4:6])
day = int(testdate[6:8])
subprocess.run('date %d-%d-%d' % (year, month, day), shell=True)
@staticmethod
def read_dbr(logger, test_pic):
reader = BarcodeReader()
# DBR 试用key,试用期30天
&nb