tkinter - show image overlay on a canvas image with mouse move
You actually did almost all of it. You just need to reposition some of the things and add a few things here and there (I'm not going to do it in a clean way otherwise I have to change more stuff. You can do that yourself later to not have duplicate lines in your code):
Change this part of your code:
# loading background and altered image into numpy array.background_image_data = imread("images/original.png", mode="L")foreground_image_data = imread("images/altered.png", mode="L")# Here is where the mouse coordinates should be injected to move the window over the background imagewindow_data = foreground_image_data[500:600, 500:600]background_image_data[500:600, 500:600] = window_dataimg = ImageTk.PhotoImage(Image.fromarray(background_image_data))canvas.create_image(0, 0,image=img,anchor="nw")canvas.config(scrollregion=canvas.bbox(ALL), width=img.width(), height=img.height())
to this:
# loading background and altered image into numpy array.background_image_data = imread("images/original.png", mode="L")foreground_image_data = imread("images/altered.png", mode="L")'''Shouldn't change the original background image becausethat way the changes will be permanent'''bg_img = background_image_data.copy() # Here is where the mouse coordinates should be injected to move the window over the background imagex,y,wh = (50,50,100)window_data = foreground_image_data[y:y+wh,x:x+wh]bg_img[y:y+wh,x:x+wh] = window_dataimg = ImageTk.PhotoImage(Image.fromarray(bg_img))canvas.create_image(0, 0,image=img,anchor="nw")canvas.config(scrollregion=canvas.bbox(ALL), width=img.width(), height=img.height())
Change
"<ButtonPress-1>"
to"<Motion>"
so it would run by change of mouse position. Or change it to"<B1-Motion>"
so it runs whenever you are holding down Left-Button and moving the mouse.Change this:
def move_window(event): cx, cy = event2canvas(event, canvas)
To this:
def move_window(event): global img cx, cy = event2canvas(event, canvas) x,y,wh = (int(cx),int(cy),100) window_data = foreground_image_data[y:y+wh,x:x+wh] bg_img = background_image_data.copy() bg_img[y:y+wh,x:x+wh] = window_data img = ImageTk.PhotoImage(Image.fromarray(bg_img)) canvas.create_image(0, 0,image=img,anchor="nw")
And you're done! As you can see it's all your own code just moved around, and with a few spices. I haven't worked with canvas very much so I don't know if that last part will keep creating new image on top of the other or replacing an already existing one. So I don't know if it's the best code to use there, but it works.
You better clean this code up because as you can see a lot of the code from move_window
is the same as it was before the mainloop
Good luck.