import tkinter as tk
from tkinter import *
from tkinter import messagebox
import sys
import os
import tkinter as tk
import requests
from PIL import Image, ImageTk
#encoding=gbk
import requests
import cv2
import numpy as np
import os
from PIL import ImageFont, ImageDraw, Image#图片显示汉字
#获取当前目录下图片
import glob
#encoding=gbk
import requests
import cv2
import numpy as np
import os
from PIL import ImageFont, ImageDraw, Image#图片显示汉字
#获取当前目录下图片
import glob
img_list=[]#存放图片,
name_list=[]#存储商品名称
zname=''
sys.path.append(".MvImport")
from MvCameraControl_class import *
import time
jiage = {'草莓': 39, '苹果': 19.8, '莲雾果': 45.2, '红色灯笼椒': 41.81, '全开盖': 120}
yuan = 0
class play:
def __init__(self):
global name_list
global yuan
global number
self.root = tk.Tk()
self.root.title("智慧零售系统")
self.root.geometry("500x700")
self.root.resizable(width=False, height=False)
self.lb2 = tk.Label(self.root, text='商品', width=15, font=('Arial', 15))
self.lb3 = tk.Label(self.root, text='售价', width=15, font=('Arial', 15))
self.listbox1 = Listbox(self.root, width=70, height=26)
self.lb1 = tk.Label(self.root, text='总价:0.00元', width=15, font=('Arial', 20))
self.b1 = tk.Button(self.root, text='继续n购物', width=5, height=2)
self.b2 = tk.Button(self.root, text='关闭n系统', width=5, height=2, command=self.end)
self.b3 = tk.Button(self.root, text='售卖n商品', width=5, height=2,command=self.xb)
self.b4 = tk.Button(self.root, text='打印n账单', width=5, height=2,command=self.dy)
self.lb1.place(x=280, y=500)
self.lb2.place(x=-60, y=0)
self.lb3.place(x=390, y=0)
self.listbox1.place(x=3, y=30)
self.b1.place(x=70, y=600)
self.b2.place(x=370, y=600)
self.b3.place(x=170, y=600)
self.b4.place(x=270, y=600)
self.root.mainloop()
def end(self):
self.root.quit()
def xb(self):
global name_list
global yuan
global zname
class HHV:
def __init__(self, index=0):
self.init_cam()
self.save_image2local(index)
self.exit_cam()
def init_cam(self, ):
deviceList = MV_CC_DEVICE_INFO_LIST()
tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
nConnectionNum = 0
# ch:创建相机实例 | en:Creat Camera Object
self.cam = MvCamera()
# ch:选择设备并创建句柄 | en:Select device and create handle
stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)],
POINTER(MV_CC_DEVICE_INFO)).contents
ret = self.cam.MV_CC_CreateHandle(stDeviceList)
# ch:打开设备 | en:Open device
ret = self.cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
# ch:设置触发模式为off | en:Set trigger mode as off
ret = self.cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
# ch:获取数据包大小 | en:Get payload size
stParam = MVCC_INTVALUE()
memset(byref(stParam), 0, sizeof(MVCC_INTVALUE))
ret = self.cam.MV_CC_GetIntValue("PayloadSize", stParam)
self.nPayloadSize = stParam.nCurValue
def save_image2local(self, index=0):
# ch:开始取流 | en:Start grab image
ret = self.cam.MV_CC_StartGrabbing()
stDeviceList = MV_FRAME_OUT_INFO_EX()
memset(byref(stDeviceList), 0, sizeof(stDeviceList))
self.data_buf = (c_ubyte * self.nPayloadSize)()
ret = self.cam.MV_CC_GetOneFrameTimeout(byref(self.data_buf), self.nPayloadSize, stDeviceList, 1000)
if ret == 0:
# print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stDeviceList.nWidth, stDeviceList.nHeight, stDeviceList.nFrameNum))
nRGBSize = stDeviceList.nWidth * stDeviceList.nHeight * 3
stConvertParam = MV_SAVE_IMAGE_PARAM_EX()
stConvertParam.nWidth = stDeviceList.nWidth
stConvertParam.nHeight = stDeviceList.nHeight
stConvertParam.pData = self.data_buf
stConvertParam.nDataLen = stDeviceList.nFrameLen
stConvertParam.enPixelType = stDeviceList.enPixelType
stConvertParam.nImageLen = stConvertParam.nDataLen
stConvertParam.nJpgQuality = 70
stConvertParam.enImageType = MV_Image_Jpeg
stConvertParam.pImageBuffer = (c_ubyte * nRGBSize)()
stConvertParam.nBufferSize = nRGBSize
# ret = self.cam.MV_CC_ConvertPixelType(stConvertParam)
# print(stConvertParam.nImageLen)
ret = self.cam.MV_CC_SaveImageEx2(stConvertParam)
if ret != 0:
print("convert pixel fail ! ret[0x%x]" % ret)
del self.data_buf
sys.exit()
file_path = "good_" + str(index) + ".jpg"
time.sleep(0.5)
file_open = open(file_path.encode('ascii'), 'wb+')
img_buff = (c_ubyte * stConvertParam.nImageLen)()
cdll.msvcrt.memcpy(byref(img_buff), stConvertParam.pImageBuffer, stConvertParam.nImageLen)
file_open.write(img_buff)
# print ("Save Image succeed!")
def exit_cam(self, ):
# ch:停止取流 | en:Stop grab image
ret = self.cam.MV_CC_StopGrabbing()
if ret != 0:
print("stop grabbing fail! ret[0x%x]" % ret)
del self.data_buf
sys.exit()
# ch:关闭设备 | Close device
ret = self.cam.MV_CC_CloseDevice()
if ret != 0:
print("close deivce fail! ret[0x%x]" % ret)
del self.data_buf
sys.exit()
# ch:销毁句柄 | Destroy handle
ret = self.cam.MV_CC_DestroyHandle()
if ret != 0:
print("destroy handle fail! ret[0x%x]" % ret)
del self.data_buf
sys.exit()
del self.data_buf
if __name__ == "__main__":
for i in range(2):
print(i, "次")
hhv = HHV()
path = r'./good_0.jpg'
with open(path, 'rb') as f:
img = f.read()
## params 为GET参数 data 为POST Body
result = requests.post('http://127.0.0.1:24401/', params={'threshold': 0.1},
data=img, ).json()
print(result['results'][0]['name'].encode('raw_unicode_escape').decode()) # 商品名称
name_list.append(result['results'][0]['name'].encode('raw_unicode_escape').decode())
print(result['results'][0]['score']) # 可信度值
txt = str(result['results'][0]['name'].encode('raw_unicode_escape').decode()) + '%.3f' %
result['results'][0]['score']
print("文本:", txt)
# 图片宽度,高度
size = cv2.imread(path).shape
img_kuan = size[1] # 宽度
img_gao = size[0] # 高度
x1 = result['results'][0]['x1'] * img_kuan
x2 = result['results'][0]['x2'] * img_kuan
y1 = result['results'][0]['y1'] * img_gao
y2 = result['results'][0]['y2'] * img_gao
print(x1, x2, y1, y2)
# zb_x1=result['results'][0]['location']['left']
# zb_y1=result['results'][0]['location']['top']
# zb_x2=result['results'][0]['location']['width']
# zb_y2=result['results'][0]['location']['height']
# print("方框坐标:n",zb_x1,zb_y1,zb_x2,zb_y2)
img = cv2.imread(path)
# 框选
draw = cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255),
8) # 参数含义:(原图,左顶点坐标,右底点坐标,颜色BGR,线条粗细)
# 在图片上添加文字 1
# 图片转换(cv2 -> pil)
cv2img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
pilimg = Image.fromarray(cv2img)
# 在图片上添加文字(支持中文)
draw = ImageDraw.Draw(pilimg)
font = ImageFont.truetype("simhei.ttf", 50, encoding="utf-8")
draw.text((int(x1), int(y1)), txt, (255, 0, 0), font=font)
# 图片转换(pil -> cv2)
img = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
cv2.namedWindow("canny", 0)
cv2.resizeWindow("canny", 300, 300) # 设置窗口大小
cv2.imshow("canny", img)
cv2.waitKey()
print("商品名称:", name_list)
for i, item in enumerate(name_list):
self.listbox1.insert(i, item + ' ' * 100 + str('%.2f' % jiage[item]) + '元')
yuan += jiage[item]
zname+=item + ' ' * 10 + str('%.2f' % jiage[item]) + '元n'
self.lb1 = tk.Label(self.root, text='总价:%.2f元' % yuan, width=15, font=('Arial', 20))
zname+='nnn'+' '*10+'总价:%.2f元' % yuan
self.lb1.place(x=280, y=500)
def dy(self):
import cv2
import os, sys
import win32print
cap = cv2.VideoCapture(0)
i = 1
while True:
# 从摄像头读取图片
sucess, img = cap.read()
# 转为灰度图片s
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 显示摄像头
cv2.imshow('----------please enter "s" to take a picture----------', img)
# 保持画面的持续,无限期等待输入
k = cv2.waitKey(1)
# k == 27 通过esc键退出摄像 ESC(ASCII码为27)
if k == 27:
break
elif k == ord("s"):
# 通过s键保存图片,并退出。
cv2.imwrite('img/lsn{}.png'.format(str(i)), img)
i += 1
# 关闭摄像头
cap.release()
cv2.destroyAllWindows()
import requests
path = 'img/lsn1.png'
with open(path, 'rb') as f:
img = f.read()
## params 为GET参数 data 为POST Body
result = requests.post('http://127.0.0.1:24402/', params={'threshold': 0.5},
data=img, ).json()
# print(result)
print(result['results'][0]['name'].encode('raw_unicode_escape').decode())
if result['results'][0]['name'].encode('raw_unicode_escape').decode() == "朱梓轩" or '李硕楠':
printer_name = win32print.GetDefaultPrinter()
if sys.version_info >= (3,):
raw_data = bytes('nnnn' + zname + 'nnnnnnnnn', "gbk")
else:
raw_data = "test"
hPrinter = win32print.OpenPrinter(printer_name)
try:
hJob = win32print.StartDocPrinter(hPrinter, 1, ("test of raw data", None, "RAW"))
try:
win32print.StartPagePrinter(hPrinter)
win32print.WritePrinter(hPrinter, raw_data)
win32print.EndPagePrinter(hPrinter)
finally:
win32print.EndDocPrinter(hPrinter)
finally:
win32print.ClosePrinter(hPrinter)
print("打印账单,请注意查收")
play()



