IDS_freeze_trigger.py 19 KB

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