Guest User

Untitled

a guest
May 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import cv2
  2. import tkinter
  3. from PIL import Image, ImageTk
  4.  
  5.  
  6. def inter_evo(solutions, geometry=None, load=False, to_pil=False):
  7. """Ask user to select one image among the set.
  8.  
  9. Will open a window with some buttons and images over those buttons,
  10. returns the index of the clicked image (button).
  11. solutions should be a list of PIL Images, but they can be paths or numpy
  12. arrays. If paths are given, use load=True. if numpy array are given, use
  13. to_pil=True. If you do not want full screen window, use geometry=(w, h).
  14. """
  15. selected = [None]
  16. root = tkinter.Tk()
  17.  
  18. def mkclk(n):
  19. def _click():
  20. selected[0] = n
  21. root.destroy()
  22. return _click
  23.  
  24. images = []
  25. # If necessary, read the images
  26. if load:
  27. # Must convert to PIL anyway
  28. to_pil = True
  29. # Load paths to cv2 images
  30. for i, sol in enumerate(solutions):
  31. sol = cv2.imread(sol, cv2.IMREAD_UNCHANGED)
  32. # RGB images are load as BGR and must be converted
  33. if len(sol.shape) == 3 and sol.shape[2] == 3:
  34. sol = cv2.cvtColor(sol, cv2.COLOR_BGR2RGB)
  35. # Replace old image
  36. images.append(sol)
  37. else:
  38. images = [i for i in solutions]
  39.  
  40. # Convert to pil if necessary
  41. if to_pil:
  42. for i, img in enumerate(images):
  43. images[i] = Image.fromarray(img)
  44.  
  45. # Set geometry and get size
  46. if geometry is not None:
  47. w, h = geometry
  48. root.geometry(f'{geometry[0]}x{geometry[1]}')
  49. else:
  50. w, h = root.winfo_screenwidth(), root.winfo_screenheight()
  51. root.attributes('-fullscreen', True)
  52.  
  53. # Compute best image size
  54. wf = w / len(images)
  55. # Resize images to fit
  56. for img in images:
  57. img.thumbnail((wf, h), Image.ANTIALIAS)
  58.  
  59. btns = []
  60. for i, sol in enumerate(images):
  61. img = ImageTk.PhotoImage(sol)
  62. btn = tkinter.Button(root,
  63. image=img,
  64. command=mkclk(i),
  65. borderwidth=0,
  66. highlightthickness=0)
  67. btn.photo = img
  68. btn.grid(row=0, column=i)
  69. btns.append(btn)
  70.  
  71. root.mainloop()
  72. print('Step complete, selected image', selected[0])
  73. return selected[0]
  74.  
  75.  
  76. def main():
  77. p = 'someimage.jpg'
  78. pics = [p, p, p]
  79. for _ in range(2):
  80. print(inter_evo(pics, load=True, to_pil=True, geometry=(300, 200)))
  81.  
  82.  
  83. if __name__ == '__main__':
  84. main()
Add Comment
Please, Sign In to add comment