实现basler进行抓拍显示
序
为了实现输入条码后,basler相机自动拍照
实现思路
就是简单的拍照,主要就是指定哪个相机拍照是个问题
代码实现
偷懒写了一个配置文件,直接从这里读取参数
GUIs
import os
import sqlite3
import tkinter as tk
from PIL import Image, ImageTk
from camera import getTime, getSavePath, getDate, cameraMain
from readTxts import readAll
# 取得输入框的值并清空输入框
def handle_enter(event):
text = entry.get()
print(text)
entry.delete(0, 'end')
img_show()
try:
sqlPath = readAll()[0][0]
connect = sqlite3.connect(sqlPath)
cur = connect.cursor()
cur.execute(
f'INSERT INTO THERE_SCAN (SCANTIME,ITEMCODE,SCANDATE) VALUES ("{getTime()}","{text}","{getDate()}")')
connect.commit()
cur.close()
connect.close()
except Exception as e:
print('Error:数据库错误')
print(e)
errorShow('数据库错误', 'red')
def load_img(index, item):
# 打开图片。
# resize():示例图片太大,这里缩小一些。
img = Image.open(item).resize((400, 300))
# 引用:添加一个Label,用来存储图片。使用PanedWindow也行。
panel = tk.Label(master=window)
panel.photo = ImageTk.PhotoImage(img) # 将原本的变量photo改为panel.photo
# 图片用Label来显示,参数master改不改为panel都行,这里就不改了。
# 注意:参数image改为panel.photo
# tk.Label(master=window, image=panel.photo).grid(row=1 + index // 2, column=index % 2)
tk.Label(master=window, image=panel.photo).place(x=100 + 800 * index // 2, y=50 + 800 * index % 2)
# 展示图片
def img_show():
try:
cameraMain()
paths = getSavePath() + '\\' + getDate() + '\\' + getTime() + '\\'
image_files = [f for f in os.listdir(paths) if os.path.isfile(os.path.join(paths, f))]
img_list = []
for imgs in image_files:
img_list.append(imgs)
for index, item in enumerate(img_list):
load_img(index, paths + item) # 执行函数
errorShow('OK', 'green')
except Exception as e:
print(e)
errorShow('相机未连接,或者相机IP未配置正确,配置正确后请重试', 'red')
def errorShow(errors, color):
showTxt = getTime()+" : "+errors
showText.config(text=showTxt, bg=color)
showText.place(x=300, y=10)
if __name__ == '__main__':
window = tk.Tk()
# 设置弹出窗口的大小
window.geometry("1000x800")
# 设置左上角图标
window.iconphoto(False, tk.PhotoImage(file='anll.png'))
window.title("扫码过站照片采集")
# 添加一个标签和一个文本框
label = tk.Label(window, text="请输入条码:")
entry = tk.Entry(window)
Timeshow = tk.Label(window)
showText = tk.Label(window)
# label.grid(row=0, column=0)
# entry.grid(row=0, column=1)
label.place(x=10, y=10)
entry.place(x=100, y=10)
# 设置焦点
entry.focus_set()
# 按回车就输入值
entry.bind("<Return>", handle_enter)
# 进入事件循环
window.mainloop()
basler
from pypylon import pylon
import cv2
# conecting to the first available camera
# camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
def savePhoto(ip_address, saveFile):
info = pylon.DeviceInfo()
info.SetPropertyValue('IpAddress', ip_address)
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice(info))
# camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
# Grabing Continusely (video) with minimal delay
camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
converter = pylon.ImageFormatConverter()
# converting to opencv bgr format
converter.OutputPixelFormat = pylon.PixelType_BGR8packed
converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
grabResult = camera.RetrieveResult(1000, pylon.TimeoutHandling_ThrowException)
if grabResult.GrabSucceeded():
# Access the image data
image = converter.Convert(grabResult)
img = image.GetArray()
# cv2.namedWindow('title', cv2.WINDOW_NORMAL)
# cv2.imshow('title', img)
# cv2.imwrite(r'F:\Desktop\1\123.jpg', img)
cv2.imencode('.jpg', img)[1].tofile(saveFile)
grabResult.Release()
# Releasing the resource
camera.StopGrabbing()
cv2.destroyAllWindows()
camera
#!/usr/bin/env python
# coding=utf-8
import datetime
import os
import cv2 as cv
from basler import savePhoto
from readTxts import readAll
now = datetime.datetime.now()
# 格式化日期和时间
formatted_date = now.strftime("%Y%m%d")
formatted_time = now.strftime("%H%M%S")
SavePath = readAll()[1][0]
def getSavePath():
return SavePath
def setTime():
global now
now = datetime.datetime.now()
global formatted_date
formatted_date = now.strftime("%Y-%m-%d")
global formatted_time
formatted_time = now.strftime("%Hh%Mm%Ss")
def getDate():
return formatted_date
def getTime():
return formatted_time
# 路径不存在就生成
def fileOrNone(File_Path):
if not os.path.exists(File_Path):
os.makedirs(File_Path)
# 本机拍照保存
def show_in_cv(camera_id):
# 获取当前日期和时间
setTime()
DayPaths = SavePath + '\\' + f'{formatted_date}'
fileOrNone(DayPaths)
datePaths = DayPaths + '\\' + f'{formatted_time}'
fileOrNone(datePaths)
# 本机拍照代码
cap = cv.VideoCapture(camera_id, cv.CAP_DSHOW)
# cap.set(cv.CAP_PROP_FRAME_WIDTH, 960)
# cap.set(cv.CAP_PROP_FRAME_HEIGHT, 540)
# cap.set(cv.CAP_PROP_FPS, 30)
suc, frame = cap.read()
# 纯英文路径保存方法
# cv.imwrite(f'{datePaths}\{camera_id}.jpg', frame)
# 中文路径保存方法
cv.imencode('.jpg', frame)[1].tofile(f'{datePaths}'+'\\'+f'{camera_id}.jpg')
# 弹窗展示功能
# cv.imshow("preview camera", frame)
# cv.waitKey(30)
def cameraMain():
# cameras = list_video_devices()
# print(f'\n\n===========================\ncamera_list: {cameras}')
# print(cameras)
# idx = 1
# camera_id = cameras[idx][0]
# camera_name = cameras[idx][1]
# print(f'\n\n===========================\npreview camera: camera_id={camera_id} camera_name={camera_name}')
# show_in_cv(camera_id)
# cameras = list_video_devices()
# print(cameras)
# for idx in cameras:
# camera_id = idx[0]
# camera_name = idx[1]
# print(camera_name)
# show_in_cv(camera_id)
setTime()
DayPaths = SavePath + '\\' + f'{formatted_date}'
fileOrNone(DayPaths)
datePaths = DayPaths + '\\' + f'{formatted_time}'
fileOrNone(datePaths)
ip_address = readAll()[3][0]
ipList = ip_address.split(',')
for index, ip in enumerate(ipList):
cameras = ip
print(ip)
saveFilePhoto = f'{datePaths}' + '\\' + f'{index}.jpg'
savePhoto(cameras, saveFilePhoto)
readTxts
def listToStr(strList):
strs = ""
if len(strList) > 0:
for i in strList:
strs = strs + i
if i != strList[-1]:
strs = strs + "\\"
return strs
# 读取同一行文字的时候
def sameLine(txt_Path, needWord):
with open(txt_Path, encoding='utf-8') as file:
words = needWord
returnWord = []
for line in file.readlines():
if line.strip().startswith(words):
returnWord.append(line.strip().replace(words, ""))
if len(returnWord) == 0:
returnWord.append("无")
return returnWord
def readAll():
try:
txt_Path = r'F:\Desktop\3期摄像头扫码拍照留像\扫码过站照片采集配置.txt'
result_list = [sameLine(txt_Path, "数据库保存路径="), sameLine(txt_Path, "照片保存总路径="),
sameLine(txt_Path, "默认图片文件夹路径="), sameLine(txt_Path, "相机IP=")]
return result_list
except Exception as e:
print("Error:0 文件读取错误")
print(e)
if __name__ == '__main__':
print(readAll())