Coffee_project_detection.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #coding=utf-8
  2. import os
  3. import numpy as np
  4. import datetime
  5. import cv2
  6. import pymysql
  7. import time
  8. import tensorflow as tf
  9. import requests as req
  10. from numba import jit
  11. from urllib import parse
  12. from PIL import Image
  13. conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='g53743001', db='coffee_detection',
  14. charset='utf8')
  15. image_size = 150
  16. cap = cv2.VideoCapture(0)
  17. def takephoto():
  18. ret, frame = cap.read()
  19. frame = cv2.resize(frame, (1936, 1096))
  20. cv2.imwrite("D:\\fatwolf\\company_files\\opencv\\2.png", frame)
  21. #cap.release()
  22. def cut_rectangle():
  23. #img = cv2.imread("D:\\fatwolf\\company_files\\opencv\\2021-05-05-11_13_47.png")
  24. img = cv2.imread("D:\\fatwolf\\company_files\\opencv\\2.png")
  25. # img = cv2.resize(img1,(968,548))
  26. # img = img.shape
  27. point_color = (0, 0, 255)
  28. # roi = img[421:527,328:369]
  29. command1 = "SELECT Name,X, X1 ,Y ,Y1 FROM `cut` WHERE Name LIKE 'roi1'"
  30. l = conn.cursor()
  31. l.execute(command1)
  32. conn.commit()
  33. r1 = l.fetchone()
  34. #print(r1[0])
  35. command2 = "SELECT Name,X, X1 ,Y ,Y1 FROM `cut` WHERE Name LIKE 'roi2'"
  36. l = conn.cursor()
  37. l.execute(command2)
  38. conn.commit()
  39. r2 = l.fetchone()
  40. #print(r2[0])
  41. command3 = "SELECT Name,X, X1 ,Y ,Y1 FROM `cut` WHERE Name LIKE 'roi3'"
  42. l = conn.cursor()
  43. l.execute(command3)
  44. conn.commit()
  45. r3= l.fetchone()
  46. #print(r3[0])
  47. command4 = "SELECT Name,X, X1 ,Y ,Y1 FROM `cut` WHERE Name LIKE 'roi4'"
  48. l = conn.cursor()
  49. l.execute(command4)
  50. conn.commit()
  51. r4 = l.fetchone()
  52. #print(r4[0])
  53. def roi1():
  54. x = r1[1]
  55. x1 = r1[2]
  56. y = r1[3]
  57. y1 = r1[4]
  58. i = 1
  59. number = 1
  60. # roi [y:y1,x:x1]
  61. # rectangle (x.y),(x1,y1)
  62. roi = img[y:y1, x:x1]
  63. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  64. roi = cv2.resize(roi,(image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  65. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_1.png', roi)
  66. # cv2.imshow("ROI_WINDOW",roi)
  67. # cv2.waitKey(0)
  68. def roi2():
  69. x = r2[1]
  70. x1 = r2[2]
  71. y = r2[3]
  72. y1 = r2[4]
  73. i = 1
  74. number = 1
  75. # roi [y:y1,x:x1]
  76. # rectangle (x.y),(x1,y1)
  77. roi = img[y:y1, x:x1]
  78. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  79. roi = cv2.resize(roi,(image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  80. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_2.png', roi)
  81. # cv2.imshow("ROI_WINDOW",roi)
  82. # cv2.waitKey(0)
  83. def roi3():
  84. x = r3[1]
  85. x1 = r3[2]
  86. y = r3[3]
  87. y1 = r3[4]
  88. i = 1
  89. # roi [y:y1,x:x1]
  90. # rectangle (x.y),(x1,y1)
  91. roi = img[y:y1, x:x1]
  92. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  93. roi = cv2.resize(roi,(image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  94. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_3.png', roi)
  95. # cv2.imshow("ROI_WINDOW",roi)
  96. # cv2.waitKey(0)
  97. def roi4():
  98. x = r4[1]
  99. x1 = r4[2]
  100. y = r4[3]
  101. y1 = r4[4]
  102. i = 1
  103. # roi [y:y1,x:x1]
  104. # rectangle (x.y),(x1,y1)
  105. roi = img[y:y1, x:x1]
  106. cv2.rectangle(img, (x, y), (x1, y1), point_color, 1)
  107. roi = cv2.resize(roi,(image_size, image_size), 0, 0, cv2.INTER_LINEAR)
  108. cv2.imwrite('D:\\fatwolf\\company_files\\paper_coffee\\pic\\' + '00_4.png', roi)
  109. # cv2.imshow("ROI_WINDOW",roi)
  110. # cv2.waitKey(0)
  111. start = datetime.datetime.now()
  112. roi1()
  113. roi2()
  114. roi3()
  115. roi4()
  116. end = datetime.datetime.now()
  117. print("cut_rectangle Run Time:", end - start)
  118. # cv2.imshow('roi1', roi1)
  119. # cv2.imshow("image", img)
  120. def cnn():
  121. # data file
  122. data_dir = "D:\\fatwolf\\company_files\\paper_coffee\\pic\\"
  123. # train or test
  124. train = False
  125. # model address
  126. model_path = "model/image_model"
  127. def read_data(data_dir):
  128. datas = []
  129. labels = []
  130. fpaths = []
  131. for fname in os.listdir(data_dir):
  132. fpath = os.path.join(data_dir, fname)
  133. fpaths.append(fpath)
  134. image = Image.open(fpath)
  135. data = np.array(image) / 255.0
  136. label = str(fname.split("_")[0])
  137. datas.append(data)
  138. labels.append(label)
  139. datas = np.array(datas)
  140. labels = np.array(labels)
  141. #print("shape of datas: {}\tshape of labels: {}".format(datas.shape, labels.shape))
  142. return fpaths, datas, labels
  143. fpaths, datas, labels = read_data(data_dir)
  144. # num_classes = len(set(labels))
  145. num_classes = 4
  146. datas_placeholder = tf.compat.v1.placeholder(tf.float32, [None, 150, 150, 3])
  147. labels_placeholder = tf.placeholder(tf.int32, [None])
  148. dropout_placeholdr = tf.placeholder(tf.float32)
  149. conv0 = tf.layers.conv2d(datas_placeholder, 20, 5, activation=tf.nn.relu)
  150. pool0 = tf.layers.max_pooling2d(conv0, [2, 2], [2, 2])
  151. conv1 = tf.layers.conv2d(pool0, 40, 4, activation=tf.nn.relu)
  152. pool1 = tf.layers.max_pooling2d(conv1, [2, 2], [2, 2])
  153. flatten = tf.layers.flatten(pool1)
  154. fc = tf.layers.dense(flatten, 400, activation=tf.nn.relu)
  155. dropout_fc = tf.layers.dropout(fc, dropout_placeholdr)
  156. logits = tf.layers.dense(dropout_fc, num_classes)
  157. predicted_labels = tf.arg_max(logits, 1)
  158. losses = tf.nn.softmax_cross_entropy_with_logits(
  159. labels=tf.one_hot(labels_placeholder, num_classes),
  160. logits=logits
  161. )
  162. mean_loss = tf.reduce_mean(losses)
  163. optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=1e-2).minimize(losses)
  164. saver = tf.compat.v1.train.Saver()
  165. with tf.compat.v1.Session() as sess:
  166. if train:
  167. print("train mode")
  168. sess.run(tf.global_variables_initializer())
  169. train_feed_dict = {
  170. datas_placeholder: datas,
  171. labels_placeholder: labels,
  172. dropout_placeholdr: 0.25
  173. }
  174. for step in range(500):
  175. _, mean_loss_val = sess.run([optimizer, mean_loss], feed_dict=train_feed_dict)
  176. if step % 50 == 0:
  177. print("step = {}\tmean loss = {}".format(step, mean_loss_val))
  178. saver.save(sess, model_path)
  179. print("train done save model{}".format(model_path))
  180. else:
  181. #start = datetime.datetime.now()
  182. #print("reloading model")
  183. saver.restore(sess, model_path)
  184. #print("{}reload model".format(model_path))
  185. label_name_dict = {
  186. 0: "Brokenbeans",
  187. 1: "Peaberry",
  188. 2: "shellbean",
  189. 3: "Worms"
  190. }
  191. test_feed_dict = {
  192. datas_placeholder: datas,
  193. labels_placeholder: labels,
  194. dropout_placeholdr: 0
  195. }
  196. predicted_labels_val = sess.run(predicted_labels, feed_dict=test_feed_dict)
  197. for fpath, real_label, predicted_label in zip(fpaths, labels, predicted_labels_val):
  198. # real_label_name = label_name_dict[real_label]
  199. predicted_label_name = label_name_dict[predicted_label]
  200. print("{}\t => {}".format(fpath, predicted_label_name))
  201. #print(fpath, predicted_label_name)
  202. dirListing = os.listdir(data_dir)
  203. #print(len(dirListing))
  204. #end = datetime.datetime.now()
  205. #print("執行時間:", end - start)
  206. x = 1
  207. #if __name__ == '__main__':
  208. while True:
  209. start = datetime.datetime.now()
  210. #takephoto()
  211. cut_rectangle()
  212. cnn()
  213. '''
  214. evt = 'notify_me' # 事件名稱
  215. key = 'c3xo5EvpBX64fPEqxphcR4jBTzDh1r2joTDsB_BslOA'
  216. val1 = parse.quote('執行第') # value1參數值
  217. val2 = parse.quote(str(x)) # value2參數值
  218. val3 = parse.quote('次') # value3參數值
  219. url = (f'https://maker.ifttt.com/trigger/{evt}' +
  220. f'/with/key/{key}?value1={val1}&value2={val2}&value3={val3}')
  221. r = req.get(url) # 執行IFTTT平台的webhooks
  222. r.text # 取得IFTTT的回應
  223. x = x+1
  224. '''
  225. end = datetime.datetime.now()
  226. print("完整執行時間:", end - start)
  227. print('-----------------------------------------------------------')
  228. #time.sleep(1)
  229. tf.reset_default_graph()