app4Stoma-old.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # https://www.notabug.org/Tonypythony/
  2. # conda create -n STOMAAPP ### C:\Users\123\miniconda3\envs
  3. ### conda activate STOMAAPP
  4. # pip install matplotlib
  5. # pip install Pillow
  6. # pip install --upgrade cx_Freeze
  7. ### conda deactivate
  8. from pathlib import Path
  9. from tkinter import filedialog
  10. from tkinter import *
  11. from PIL import ImageTk, Image #, ImageFont, ImageDraw
  12. from time import time
  13. from pylab import imshow, array, ginput, close # Matplotlib по умолчанию использует формат RGB
  14. root = Tk()
  15. current_dir = Path.cwd() # путь текущей директории
  16. filename = filedialog.askopenfilename(initialdir = current_dir, # initialdir = "/run/media/rick/DATA/Kazahi"
  17. title = "Select imagefile", filetypes = (("JPG files", "*.JPG"),("jpeg files", "*.jpeg"),
  18. ("jpg files", "*.jpg"),("png files", "*.png"),
  19. ("bmp files", "*.bmp"),("all files", "*.*")))
  20. # print(root.winfo_screenwidth())
  21. # print(root.winfo_screenheight())
  22. x_size_screen = int(root.winfo_screenwidth()/3)
  23. y_size_screen = int(root.winfo_screenheight()/3)
  24. # print(x_size_screen)
  25. # print(y_size_screen)
  26. image = Image.open(filename).convert('RGB')#.convert('L')
  27. print(image.size[0],image.size[1],image.size[0]*image.size[1])
  28. s_0 = image.size[0]*image.size[1]
  29. #print(f's_0 = {s_0}')
  30. def color_of_points(img):
  31. im = array(image)
  32. imshow(im)
  33. print('\nPlease click 2 points for crop colors')
  34. x = ginput(2)
  35. y = [(int(p), int(q)) for p, q in x]
  36. a = [y[0][0], y[0][1], y[1][0], y[1][1]]
  37. #print(a)
  38. global im_crop
  39. im_crop = image.crop((y[0][0], y[0][1], y[1][0], y[1][1]))
  40. imshow(im_crop)
  41. print('\nPlease click 2 points for detect colors')
  42. x = ginput(2)
  43. y = [(int(p), int(q)) for p, q in x]
  44. #print('You clicked: ', y)
  45. a = [y[0][0], y[0][1], y[1][0], y[1][1]]
  46. #print(a)
  47. clr1 = image.getpixel(y[0])
  48. clr2 = image.getpixel(y[1])
  49. close() # закрыть окно с выбором точек
  50. print('Color 1 point is', clr1) # color of the first selected pixel
  51. print('Color 2 point is', clr2) # color of the second selected pixel
  52. color_of_points(image)
  53. image = im_crop
  54. #print(image.size[0],image.size[1],image.size[0]*image.size[1])
  55. s_1 = image.size[0]*image.size[1]
  56. k_result = s_1/s_0 # коррекция результата -- компенсация площади из-за отрезанного куска изображения
  57. k_result = round(k_result, 2)
  58. #print(f's_1 = {s_1}, s_0 = {s_0}, k_result = {k_result}')
  59. image = im_crop.resize((x_size_screen,y_size_screen)) #((536,356))
  60. #print(image.size[0],image.size[1],image.size[0]*image.size[1])
  61. x_size_root = x_size_screen + 350
  62. y_size_root = y_size_screen + 370
  63. root.geometry('{}x{}'.format(x_size_root,y_size_root)) #(536,506))
  64. canvas = Canvas(root,width=x_size_screen,height=y_size_screen)
  65. canvas.pack()
  66. pilimage = ImageTk.PhotoImage(image)
  67. imagesprite = canvas.create_image(0,0,image=pilimage, anchor=NW)
  68. container = Frame() # создаём контейнер на главном окне для расположения кнопок и полей ввода
  69. container.pack(side='top', fill='both', expand=True)
  70. redM = 255 # max
  71. redL = 0 # min
  72. greenM = 255 # max
  73. greenL = 0 # min
  74. blueM = 255 # max
  75. blueL = 0 # min
  76. ########################################################################
  77. lbl1 = Label(container, text="RedMax = ")
  78. lbl1.grid(column=6, row=1)
  79. def get_val_motion1(event):
  80. global redM
  81. redM = scal1.get()
  82. scal1 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  83. tickinterval=20, resolution=1)
  84. scal1.bind("<B1-Motion>", get_val_motion1)
  85. scal1.grid(column=7, row=1)
  86. ########################################################################
  87. lbl2 = Label(container, text="RedMin = ")
  88. lbl2.grid(column=6, row=2)
  89. def get_val_motion2(event_1):
  90. global redL
  91. redL = scal2.get()
  92. scal2 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  93. tickinterval=20, resolution=1)
  94. scal2.bind("<B1-Motion>", get_val_motion2)
  95. scal2.grid(column=7, row=2)
  96. ########################################################################
  97. lbl3 = Label(container, text="GreenMax = ")
  98. lbl3.grid(column=6, row=3)
  99. def get_val_motion3(event):
  100. global greenM
  101. greenM = sca3.get()
  102. sca3 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  103. tickinterval=20, resolution=1)
  104. sca3.bind("<B1-Motion>", get_val_motion3)
  105. sca3.grid(column=7, row=3)
  106. ########################################################################
  107. lbl4 = Label(container, text="GreenMin = ")
  108. lbl4.grid(column=6, row=4)
  109. def get_val_motion4(event_1):
  110. global greenL
  111. greenL = scal4.get()
  112. scal4 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  113. tickinterval=20, resolution=1)
  114. scal4.bind("<B1-Motion>", get_val_motion4)
  115. scal4.grid(column=7, row=4)
  116. ########################################################################
  117. lbl5 = Label(container, text="BlueMax = ")
  118. lbl5.grid(column=6, row=5)
  119. def get_val_motion5(event):
  120. global blueM
  121. blueM = scal5.get()
  122. scal5 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  123. tickinterval=20, resolution=1)
  124. scal5.bind("<B1-Motion>", get_val_motion5)
  125. scal5.grid(column=7, row=5)
  126. ########################################################################
  127. lbl6 = Label(container, text="BlueMin = ")
  128. lbl6.grid(column=6, row=6)
  129. def get_val_motion6(event_1):
  130. global blueL
  131. blueL = scal6.get()
  132. scal6 = Scale(container, orient=HORIZONTAL, length=int(image.size[0]*0.6), from_=0, to=255,
  133. tickinterval=20, resolution=1)
  134. scal6.bind("<B1-Motion>", get_val_motion6)
  135. scal6.grid(column=7, row=6)
  136. ########################################################################
  137. def my_callback3(): # показывает исходную фотографию
  138. #print('return button pushed')
  139. global pilimage
  140. pilimage = ImageTk.PhotoImage(image)
  141. global imagesprite
  142. #imagesprite = canvas.create_image(int(image.size[0]*kx_imagesprite),int(image.size[1]*kx_imagesprite),image=pilimage)
  143. imagesprite = canvas.create_image(0,0,image=pilimage, anchor=NW)
  144. button3 = Button(container , text="Source" , command=my_callback3)
  145. button3.grid(row=3 ,column=0)
  146. ########################################################################
  147. def my_callback4(): # сохраняет результат
  148. file_name = filedialog.asksaveasfilename(initialdir = current_dir,
  149. filetypes = (("png files", "*.png"),
  150. ("jpg files", "*.jpg"),
  151. ("bmp files", "*.bmp"),("all files", "*.*")), defaultextension="")
  152. global new_image
  153. new_image.save(file_name)
  154. button4 = Button(container , text="Save Result" , command=my_callback4)
  155. button4.grid(row=2 ,column=0)
  156. ########################################################################
  157. def my_callback6(): # открыть новое маленькое изображение
  158. global filename
  159. filename = filedialog.askopenfilename(initialdir = current_dir, # initialdir = "/run/media/rick/DATA/Kazahi"
  160. title = "Select imagefile", filetypes = (("JPG files", "*.JPG"),("jpeg files", "*.jpeg"),
  161. ("jpg files", "*.jpg"),("png files", "*.png"),
  162. ("bmp files", "*.bmp"),("all files", "*.*")))
  163. global image
  164. image = Image.open(filename).convert('RGB')
  165. color_of_points(image)
  166. image = image.resize((x_size_screen,y_size_screen)) #((536,356))
  167. global pilimage
  168. pilimage = ImageTk.PhotoImage(image)
  169. global imagesprite
  170. #imagesprite = canvas.create_image(int(image.size[0]*kx_imagesprite),int(image.size[1]*kx_imagesprite),image=pilimage)
  171. imagesprite = canvas.create_image(0,0,image=pilimage, anchor=NW)
  172. button6 = Button(container , text="Open New Image" , command=my_callback6)
  173. button6.grid(row=4 ,column=0)
  174. ########################################################################
  175. def my_callback7(): # главная функция - для расчёта маленького изображения
  176. N = 0 # счётчик
  177. new_im = []
  178. start = time() # для тестирования скорости работы
  179. for i in range(image.size[0]):
  180. for j in range(image.size[1]):
  181. if (image.getpixel((i,j))[0] >= redL) and (image.getpixel((i,j))[0] <= redM) \
  182. and (image.getpixel((i,j))[1] >= greenL) and (image.getpixel((i,j))[1] <= greenM) \
  183. and (image.getpixel((i,j))[2] >= blueL) and (image.getpixel((i,j))[2] <= blueM):
  184. N += 1
  185. new_im.append((i,j,image.getpixel((i,j))))
  186. #global percent
  187. percent = (N/(image.size[0]*image.size[1])*100)*k_result
  188. print("\nResult: {0:.1f}%".format(percent))
  189. print("RedL = %d; RedM = %d, \nGreenL = %d; GreenM = %d, \nBlueL = %d; \
  190. BlueM = %d".format(redL, redM, greenL, greenM, blueL, blueM))
  191. print("Time {0:.3f} s".format(float(round((time()-start)*1e3)/1e3))) # для тестирования скорости работы
  192. global new_image # нужно для возможности сохранения в дальнейшем
  193. new_image = Image.new("RGB", (image.size[0], image.size[1]))
  194. for i in range(len(new_im)):
  195. new_image.putpixel((new_im[i][0], new_im[i][1]), new_im[i][2])
  196. global pilimage
  197. pilimage = ImageTk.PhotoImage(new_image)
  198. global imagesprite
  199. imagesprite = canvas.create_image(0,0,image=pilimage, anchor=NW)
  200. button7 = Button(container , text="Result" , command=my_callback7)
  201. button7.grid(row=1 ,column=0)
  202. root.mainloop()