IDS_ringbuffer_while.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #===========================================================================#
  2. # #
  3. # Copyright (C) 2006 - 2018 #
  4. # IDS Imaging Development Systems GmbH #
  5. # Dimbacher Str. 6-8 #
  6. # D-74182 Obersulm, Germany #
  7. # #
  8. # The information in this document is subject to change without notice #
  9. # and should not be construed as a commitment by IDS Imaging Development #
  10. # Systems GmbH. IDS Imaging Development Systems GmbH does not assume any #
  11. # responsibility for any errors that may appear in this document. #
  12. # #
  13. # This document, or source code, is provided solely as an example #
  14. # of how to utilize IDS software libraries in a sample application. #
  15. # IDS Imaging Development Systems GmbH does not assume any responsibility #
  16. # for the use or reliability of any portion of this document or the #
  17. # described software. #
  18. # #
  19. # General permission to copy or modify, but not for profit, is hereby #
  20. # granted, provided that the above copyright notice is included and #
  21. # reference made to the fact that reproduction privileges were granted #
  22. # by IDS Imaging Development Systems GmbH. #
  23. # #
  24. # IDS Imaging Development Systems GmbH cannot assume any responsibility #
  25. # for the use or misuse of any portion of this software for other than #
  26. # its intended diagnostic purpose in calibrating and testing IDS #
  27. # manufactured cameras and software. #
  28. # #
  29. #===========================================================================#
  30. # Developer Note: I tried to let it as simple as possible.
  31. # Therefore there are no functions asking for the newest driver software or freeing memory beforehand, etc.
  32. # The sole purpose of this program is to show one of the simplest ways to interact with an IDS camera via the uEye API.
  33. # (XS cameras are not supported)
  34. #---------------------------------------------------------------------------------------------------------------------------------------
  35. #coding=utf-8
  36. #Libraries
  37. from ctypes import *
  38. from pyueye import ueye
  39. import numpy as np
  40. import cv2
  41. import sys
  42. import ctypes
  43. import struct
  44. import threading
  45. import time
  46. import datetime
  47. import os
  48. import pymysql
  49. import tensorflow as tf
  50. import requests as req
  51. import sys
  52. import mysql.connector
  53. from mysql.connector import Error
  54. from urllib import parse
  55. from PIL import Image
  56. #---------------------------------------------------------------------------------------------------------------------------------------
  57. #Variables
  58. hCam = ueye.HIDS(0) #0: first available camera; 1-254: The camera with the specified camera ID
  59. sInfo = ueye.SENSORINFO()
  60. cInfo = ueye.CAMINFO()
  61. pcImageMemory = ueye.c_mem_p()
  62. MemID = ueye.int()
  63. rectAOI = ueye.IS_RECT()
  64. pitch = ueye.INT()
  65. nBitsPerPixel = ueye.INT(24) #24: bits per pixel for color mode; take 8 bits per pixel for monochrome
  66. channels = 3 #3: channels for color mode(RGB); take 1 channel for monochrome
  67. m_nColorMode = ueye.INT() # Y8/RGB16/RGB24/REG32
  68. bytes_per_pixel = int(nBitsPerPixel / 8)
  69. formatInfo=ueye.IMAGE_FORMAT_INFO()
  70. now=ctypes.c_uint()
  71. m_pcSeqImgMem=[]
  72. m_lSeqMemId=[]
  73. nNum=ueye.INT()
  74. pcMem=ueye.c_mem_p()
  75. pcMemLast=ueye.c_mem_p()
  76. ImageFileParams=ueye.IMAGE_FILE_PARAMS()
  77. ueye.is_FreeImageMem(hCam, pcImageMemory, MemID)
  78. conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='g53743001',
  79. db='coffee_detection',
  80. charset='utf8')
  81. #---------------------------------------------------------------------------------------------------------------------------------------
  82. print("START")
  83. #print()
  84. # Starts the driver and establishes the connection to the camera
  85. nRet = ueye.is_InitCamera(hCam, None)
  86. if nRet != ueye.IS_SUCCESS:
  87. ueye.is_InitCamera(hCam, None)
  88. #print("is_InitCamera ERROR")
  89. ueye.is_ParameterSet(hCam,ueye.IS_PARAMETERSET_CMD_LOAD_EEPROM,None,0)
  90. # Reads out the data hard-coded in the non-volatile camera memory and writes it to the data structure that cInfo points to
  91. nRet = ueye.is_GetCameraInfo(hCam, cInfo)
  92. if nRet != ueye.IS_SUCCESS:
  93. print("is_GetCameraInfo ERROR")
  94. # You can query additional information about the sensor type used in the camera
  95. nRet = ueye.is_GetSensorInfo(hCam, sInfo)
  96. if nRet != ueye.IS_SUCCESS:
  97. print("is_GetSensorInfo ERROR")
  98. # Set display mode to DIB
  99. nRet = ueye.is_SetDisplayMode(hCam, ueye.IS_SET_DM_DIB)
  100. # Set the right color mode
  101. if int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_BAYER:
  102. # setup the color depth to the current windows setting
  103. ueye.is_GetColorDepth(hCam, nBitsPerPixel, m_nColorMode)
  104. bytes_per_pixel = int(nBitsPerPixel / 8)
  105. #print("IS_COLORMODE_BAYER: ", )
  106. #print("\tm_nColorMode: \t\t", m_nColorMode)
  107. #print("\tnBitsPerPixel: \t\t", nBitsPerPixel)
  108. #print("\tbytes_per_pixel: \t\t", bytes_per_pixel)
  109. #print()
  110. elif int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_CBYCRY:
  111. # for color camera models use RGB32 mode
  112. m_nColorMode = ueye.IS_CM_BGR8_PACKED
  113. nBitsPerPixel = ueye.INT(24)
  114. bytes_per_pixel = int(nBitsPerPixel / 8)
  115. #print("IS_COLORMODE_CBYCRY: ", )
  116. #print("\tm_nColorMode: \t\t", m_nColorMode)
  117. #print("\tnBitsPerPixel: \t\t", nBitsPerPixel)
  118. #print("\tbytes_per_pixel: \t\t", bytes_per_pixel)
  119. #print()
  120. elif int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_MONOCHROME:
  121. # for color camera models use RGB32 mode
  122. m_nColorMode = ueye.IS_CM_MONO8
  123. nBitsPerPixel = ueye.INT(8)
  124. bytes_per_pixel = int(nBitsPerPixel / 8)
  125. #print("IS_COLORMODE_MONOCHROME: ", )
  126. #print("\tm_nColorMode: \t\t", m_nColorMode)
  127. #print("\tnBitsPerPixel: \t\t", nBitsPerPixel)
  128. #print("\tbytes_per_pixel: \t\t", bytes_per_pixel)
  129. #print()
  130. else:
  131. # for monochrome camera models use Y8 mode
  132. m_nColorMode = ueye.IS_CM_MONO8
  133. nBitsPerPixel = ueye.INT(8)
  134. bytes_per_pixel = int(nBitsPerPixel / 8)
  135. print("else")
  136. ueye.is_SetColorMode(hCam,ueye.IS_CM_BGRA8_PACKED)
  137. nBitsPerPixel=ueye.INT(32)
  138. # Can be used to set the size and position of an "area of interest"(AOI) within an image
  139. nRet = ueye.is_AOI(hCam, ueye.IS_AOI_IMAGE_GET_AOI, rectAOI, ueye.sizeof(rectAOI))
  140. if nRet != ueye.IS_SUCCESS:
  141. print("is_AOI ERROR")
  142. width =rectAOI.s32Width
  143. height =rectAOI.s32Height
  144. # Prints out some information about the camera and the sensor
  145. #print("Camera model:\t\t", sInfo.strSensorName.decode('utf-8'))
  146. #print("Camera serial no.:\t", cInfo.SerNo.decode('utf-8'))
  147. #print("Maximum image width:\t", width)
  148. #print("Maximum image height:\t", height)
  149. #print()
  150. #---------------------------------------------------------------------------------------------------------------------------------------
  151. for i in range(1,5):
  152. # Allocates an image memory for an image having its dimensions defined by width and height and its color depth defined by nBitsPerPixel
  153. nRet = ueye.is_AllocImageMem(hCam, width, height, nBitsPerPixel, pcImageMemory, MemID)
  154. # m_pcSeqImgMem.append(pcImageMemory)
  155. # m_lSeqMemId.append(MemID)
  156. ueye.is_AddToSequence(hCam,pcImageMemory,MemID)
  157. #path=ueye.c_wchar_p()
  158. #print(type(path))
  159. #nRet = ueye.is_ParameterSet(hCam, ueye.IS_PARAMETERSET_CMD_LOAD_FILE, path, 0)
  160. # Activates the camera's live video mode (free run mode)
  161. nRet = ueye.is_CaptureVideo(hCam, ueye.IS_DONT_WAIT)
  162. if nRet != ueye.IS_SUCCESS:
  163. print("is_CaptureVideo ERROR")
  164. nRet = ueye.is_InquireImageMem(hCam, pcImageMemory, MemID, width, height, nBitsPerPixel, pitch)
  165. if nRet != ueye.IS_SUCCESS:
  166. print("is_InquireImageMem ERROR")
  167. else:
  168. print("Press q to leave the programm")
  169. Count=0
  170. def cut_rectangle():
  171. image_size = 150
  172. # img = cv2.imread("D:\\fatwolf\\company_files\\opencv\\2021-05-05-11_13_47.png")
  173. # img = cv2.imread("D:\\fatwolf\\company_files\\opencv\\2.png")
  174. #img = cv2.imread("C:\\Users\\User\\Desktop\\tfcoffebean\\test\\1.png")
  175. # img = cv2.imread("C:\\Users\\User\\Desktop\\IDS\\p\\12033_248.png")
  176. # img_size = img.shape
  177. # print(img_size)
  178. img = cv2.imread('D:\\fatwolf\\company_files\\python_code\\test_code\\test_pic\\12033_267.png')
  179. # img = cv2.resize(img1,(968,548))
  180. point_color = (0, 0, 255)
  181. command1 = "SELECT Name,X, X1 ,Y ,Y1 FROM `cut` WHERE Name LIKE 'roi1'"
  182. l = conn.cursor()
  183. l.execute(command1)
  184. conn.commit()
  185. r1 = l.fetchone()
  186. # print(r1[0])
  187. count = 1
  188. def roi1():
  189. # x = r1[1]
  190. # x1 = r1[2]
  191. # y = r1[3]
  192. # y1 = r1[4]
  193. #x = 743
  194. #x1 = 892
  195. #y = 17
  196. #y1 = 164
  197. x = 1257
  198. x1 = 1355
  199. y = 185
  200. y1 = 278
  201. i = 1
  202. i1 = 1
  203. i2 = 1
  204. i3 = 1
  205. i4 = 1
  206. i5 = 1
  207. i6 = 1
  208. number = count
  209. for i in range(6):
  210. roi = img[y:y1, x:x1]
  211. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  212. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  213. cv2.imwrite('D:\\fatwolf\\company_files\\python_code\\test_code\\test_pic\\pic' + '00_' + str(number) + '.png', roi)
  214. number = number + 1
  215. y = y + 150
  216. y1 = y1 + 150
  217. x = x + 145
  218. x1 = x1 + 145
  219. y = 1355
  220. y1 = 278
  221. '''
  222. for i in range(6):
  223. roi = img[y:y1, x:x1]
  224. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  225. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  226. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  227. number = number + 1
  228. x = x + 150
  229. x1 = x1 + 150
  230. y = y + 145
  231. y1 = y1 + 145
  232. x = 1257
  233. x1 = 1355
  234. '''
  235. '''
  236. for i1 in range(6):
  237. roi = img[y:y1, x:x1]
  238. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  239. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  240. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  241. number = number + 1
  242. x = x + 150
  243. x1 = x1 + 150
  244. y = y + 145
  245. y1 = y1 + 145
  246. x = 743
  247. x1 = 892
  248. for i2 in range(6):
  249. roi = img[y:y1, x:x1]
  250. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  251. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  252. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  253. number = number + 1
  254. x = x + 150
  255. x1 = x1 + 150
  256. y = y + 145
  257. y1 = y1 + 145
  258. x = 743
  259. x1 = 892
  260. for i3 in range(6):
  261. roi = img[y:y1, x:x1]
  262. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  263. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  264. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  265. number = number + 1
  266. x = x + 150
  267. x1 = x1 + 150
  268. y = y + 145
  269. y1 = y1 + 145
  270. x = 743
  271. x1 = 892
  272. for i4 in range(6):
  273. roi = img[y:y1, x:x1]
  274. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  275. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  276. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  277. number = number + 1
  278. x = x + 150
  279. x1 = x1 + 150
  280. y = y + 145
  281. y1 = y1 + 145
  282. x = 743
  283. x1 = 892
  284. for i5 in range(6):
  285. roi = img[y:y1, x:x1]
  286. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  287. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  288. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  289. number = number + 1
  290. x = x + 150
  291. x1 = x1 + 150
  292. y = y + 145
  293. y1 = y1 + 145
  294. x = 743
  295. x1 = 892
  296. for i6 in range(6):
  297. roi = img[y:y1, x:x1]
  298. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  299. roi = cv2.resize(roi, (image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  300. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_' + str(number) + '.png', roi)
  301. number = number + 1
  302. x = x + 150
  303. x1 = x1 + 150
  304. y = y + 145
  305. y1 = y1 + 145
  306. x = 743
  307. x1 = 892
  308. '''
  309. start = datetime.datetime.now()
  310. roi1()
  311. end = datetime.datetime.now()
  312. print("cut_rectangle Run Time:", end - start)
  313. def cnn():
  314. # data file
  315. data_dir = r"D:\\fatwolf\\company_files\\python_code\\test_code\\test_pic\\pic"
  316. print(data_dir)
  317. allName = os.listdir(data_dir)
  318. # train or test
  319. train = False
  320. # model address
  321. model_path = "model/image_model"
  322. allTestDataName = []
  323. def read_data(data_dir):
  324. datas = []
  325. labels = []
  326. fpaths = []
  327. for filename in os.listdir(data_dir):
  328. fpath = os.path.join(data_dir, filename)
  329. allTestDataName.append(filename)
  330. image = Image.open(fpath)
  331. data = np.array(image) / 255.0
  332. label = int(filename.split("_")[0])
  333. datas.append(data)
  334. labels.append(label)
  335. # allTestDataName.append(filename)
  336. datas = np.array(datas)
  337. labels = np.array(labels)
  338. allTestDataName.sort(key=lambda x: int(x[:-4]))
  339. # print(allTestDataName)
  340. # print("shape of datas: {}\tshape of labels: {}".format(datas.shape, labels.shape))
  341. return allTestDataName, datas, labels
  342. allTestDataName, datas, labels = read_data(data_dir)
  343. # num_classes = len(set(labels))
  344. num_classes = 4
  345. datas_placeholder = tf.compat.v1.placeholder(tf.float32, [None, 150, 150, 3])
  346. labels_placeholder = tf.compat.v1.placeholder(tf.int32, [None])
  347. dropout_placeholdr = tf.compat.v1.placeholder(tf.float32)
  348. conv0 = tf.layers.conv2d(datas_placeholder, 20, 5, activation=tf.nn.relu)
  349. pool0 = tf.layers.max_pooling2d(conv0, [2, 2], [2, 2])
  350. conv1 = tf.layers.conv2d(pool0, 40, 4, activation=tf.nn.relu)
  351. pool1 = tf.layers.max_pooling2d(conv1, [2, 2], [2, 2])
  352. flatten = tf.layers.flatten(pool1)
  353. fc = tf.layers.dense(flatten, 400, activation=tf.nn.relu)
  354. dropout_fc = tf.layers.dropout(fc, dropout_placeholdr)
  355. logits = tf.layers.dense(dropout_fc, num_classes)
  356. predicted_labels = tf.arg_max(logits, 1)
  357. losses = tf.nn.softmax_cross_entropy_with_logits(
  358. labels=tf.one_hot(labels_placeholder, num_classes),
  359. logits=logits
  360. )
  361. mean_loss = tf.reduce_mean(losses)
  362. optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=1e-2).minimize(losses)
  363. saver = tf.compat.v1.train.Saver()
  364. with tf.compat.v1.Session() as sess:
  365. if train:
  366. print("train mode")
  367. sess.run(tf.global_variables_initializer())
  368. train_feed_dict = {
  369. datas_placeholder: datas,
  370. labels_placeholder: labels,
  371. dropout_placeholdr: 0.25
  372. }
  373. for step in range(500):
  374. _, mean_loss_val = sess.run([optimizer, mean_loss], feed_dict=train_feed_dict)
  375. if step % 50 == 0:
  376. print("step = {}\tmean loss = {}".format(step, mean_loss_val))
  377. saver.save(sess, model_path)
  378. print("train done save model{}".format(model_path))
  379. else:
  380. # print("reloading model")
  381. saver.restore(sess, model_path)
  382. # print("{}reload model".format(model_path))
  383. label_name_dict = {
  384. 0: "Brokenbeans",
  385. 1: "Peaberry",
  386. 2: "shellbean",
  387. 3: "Worms"
  388. }
  389. test_feed_dict = {
  390. datas_placeholder: datas,
  391. labels_placeholder: labels,
  392. dropout_placeholdr: 0
  393. }
  394. predicted_labels_val = sess.run(predicted_labels, feed_dict=test_feed_dict)
  395. for fpath, real_label, predicted_label in zip(allTestDataName, labels, predicted_labels_val):
  396. real_label_name = label_name_dict[real_label]
  397. # print("訓練前",real_label_name)
  398. predicted_label_name = label_name_dict[predicted_label]
  399. # print("訓練後",predicted_label_name)
  400. # print("{}\t => {}".format(fpath, predicted_label_name))
  401. fpath = os.path.basename(fpath)
  402. print(f"{fpath}\t => {predicted_label_name}")
  403. path1 = 'output.txt'
  404. f = open(path1, 'a+')
  405. f.write(f"{fpath} => {predicted_label_name}""\n")
  406. f.close()
  407. if predicted_label_name == "shellbean" or "Peaberry" or "Worms":
  408. print("觸發噴嘴")
  409. else:
  410. print('沒有觸發')
  411. '''
  412. sqlStuff = "INSERT INTO result(picname,identify)""VALUES (%s,%s)"
  413. data = [(fpath, predicted_label_name)]
  414. a = conn.cursor()
  415. a.executemany(sqlStuff, data)
  416. conn.commit()
  417. try:
  418. connection = mysql.connector.connect(
  419. host='127.0.0.1', # 主機名稱
  420. database='coffee_detection', # 資料庫名稱
  421. user='root', # 帳號
  422. password='g53743001') # 密碼
  423. # 新增資料
  424. sql = "INSERT INTO result(picname,identify)""VALUES (%s,%s)"
  425. new_data = ("test", "test2")
  426. cursor = connection.cursor()
  427. cursor.execute(sql, new_data)
  428. # 確認資料有存入資料庫
  429. connection.commit()
  430. except Error as e:
  431. print("資料庫連接失敗:", e)
  432. finally:
  433. if (connection.is_connected()):
  434. cursor.close()
  435. connection.close()
  436. '''
  437. dirListing = os.listdir(data_dir)
  438. # print(len(dirListing))
  439. while(nRet == ueye.IS_SUCCESS):
  440. start = datetime.datetime.now()
  441. ueye.is_GetActSeqBuf(hCam, nNum, pcMem, pcMemLast)
  442. array = ueye.get_data(pcMemLast, width, height, nBitsPerPixel, pitch, copy=False)
  443. bytes_per_pixel = int(nBitsPerPixel / 8)
  444. # ...reshape it in an numpy array...
  445. frame = np.reshape(array,(height.value, width.value, bytes_per_pixel))
  446. # ...resize the image by a half
  447. frame = cv2.resize(frame,(0,0),fx=0.5, fy=0.5)
  448. #---------------------------------------------------------------------------------------------------------------------------------------
  449. #Include image data processing here
  450. Count = Count + 1
  451. '''
  452. if cv2.waitKey(2) & 0xFF == ord('p'):
  453. Count=Count+1
  454. ImageFileParams.pwchFileName = ueye.c_wchar_p('C:\\Users\\User\\Desktop\\test\\1.png')
  455. #ImageFileParams.pnImageID = &nID;
  456. #ImageFileParams.ppcImageMem = &pcMemory;
  457. ImageFileParams.nFileType = ueye.IS_IMG_PNG
  458. #ImageFileParams.ppcImageMem = pcMemLast;
  459. ImageFileParams.nQuality = 75
  460. nRet = ueye.is_ImageFile(hCam, ueye.IS_IMAGE_FILE_CMD_SAVE, ImageFileParams, ueye.sizeof(ImageFileParams));
  461. print(Count)
  462. print(nRet)
  463. '''
  464. #---------------------------------------------------------------------------------------------------------------------------------------
  465. #...and finally display it
  466. start3 = datetime.datetime.now()
  467. #cv2.imshow("SimpleLive_Python_uEye_OpenCV", frame)
  468. time.sleep(0.3)
  469. ImageFileParams.pwchFileName = ueye.c_wchar_p('C:\\Users\\User\\Desktop\\tfcoffebean\\test\\1.png')
  470. ImageFileParams.nFileType = ueye.IS_IMG_PNG
  471. ImageFileParams.nQuality = 75
  472. nRet = ueye.is_ImageFile(hCam, ueye.IS_IMAGE_FILE_CMD_SAVE, ImageFileParams, ueye.sizeof(ImageFileParams));
  473. print(Count)
  474. print(nRet)
  475. end3 = datetime.datetime.now()
  476. print("拍照執行時間:", end3 - start3)
  477. cut_rectangle()
  478. start2 = datetime.datetime.now()
  479. cnn()
  480. end2 = datetime.datetime.now()
  481. print("辨識執行時間:", end2 - start2)
  482. end = datetime.datetime.now()
  483. print("完整執行時間:", end - start)
  484. print('-----------------------------------------------------------')
  485. tf.reset_default_graph()
  486. # Press q if you want to end the loop
  487. if cv2.waitKey(1) & 0xFF == ord('q'):
  488. break
  489. #---------------------------------------------------------------------------------------------------------------------------------------
  490. # Releases an image memory that was allocated using is_AllocImageMem() and removes it from the driver management
  491. ueye.is_FreeImageMem(hCam, pcImageMemory, MemID)
  492. # Disables the hCam camera handle and releases the data structures and memory areas taken up by the uEye camera
  493. ueye.is_ExitCamera(hCam)
  494. # Destroys the OpenCv windows
  495. cv2.destroyAllWindows()
  496. #print()
  497. print("END")