Unable to write text on mouseclick area on Image

2024/11/16 17:37:41

I am trying to draw text on Image where the user clicks. Getting this error:

Exception in Tkinter callback
Traceback (most recent call last):File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__return self.func(*args)File "C:/Users/Admin/PycharmProjects/ashish/td.py", line 35, in draw_textcv2.putText(img, "OpenCV + Jurassic Park!!!", (event.x,event.y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
TypeError: Expected cv::UMat for argument 'img'
if __name__ == "__main__":root = Tk()frame = Frame(root, bd=2, relief=SUNKEN)canvas = Canvas(frame, bd=0)canvas.grid(row=0, column=0, sticky=N+S+E+W)frame.pack(fill=BOTH,expand=1)#adding the imageFile = filedialog.askopenfilename(parent=root, initialdir="F:/",title='Choose an image.')img = ImageTk.PhotoImage(Image.open(File))canvas.create_image(0,0,image=img,anchor="nw")#function to be called when mouse is clickeddef draw_text(event):cv2.putText(img, "OpenCV + Jurassic Park!!!", (event.x,event.y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)cv2.imshow("Text", img)#mouseclick eventcanvas.bind("<Button 1>",draw_text)root.mainloop()
Answer

Your img is ImageTK object from tkinter but cv2 is not part of tkinter and cv2.putText doesn't work with ImageTK. It needs something different. cv2 has own function to read image and it creates object which you can use with cv2.putText().

But canvas has function to display text on top of image and you don't need cv2. But it can't be saved in file as image with text.

But Image has function to draw text on image and it can be saved in file.

So finally you don't need cv2.


I use Image.Draw to create object on which I can put text or draw line/square/etc.
After adding text I replace image on canvas.

This method create image with text which you can save in file (img.save())

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk, ImageDraw# function to be called when mouse is clicked
def draw_text(event):global imgtkglobal cv_img# create object for drawingdraw = ImageDraw.Draw(img)# put textdraw.text((event.x,event.y), "ImageDraw + Jurassic Park!!!")# replace old imagecanvas.delete(cv_img_id)    imgtk = ImageTk.PhotoImage(img)cv_img_id = canvas.create_image(0, 0, image=imgtk, anchor="nw")if __name__ == "__main__":root = Tk()frame = Frame(root, bd=2, relief=SUNKEN)frame.pack(fill=BOTH, expand=1)canvas = Canvas(frame, bd=0)canvas.grid(row=0, column=0, sticky=N+S+E+W)#adding the imagefile = filedialog.askopenfilename(parent=root, initialdir="F:/",title='Choose an image.')img = Image.open(file)imgtk = ImageTk.PhotoImage(img)cv_img_id = canvas.create_image(0, 0, image=imgtk, anchor="nw")#mouseclick eventcanvas.bind("<Button 1>", draw_text)root.mainloop()

Using canvas.create_text you can put text on top of image which you can move/remove later but it doesn't create image with text which you can save in file.

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk# function to be called when mouse is clicked
def draw_text(event):canvas.create_text((event.x,event.y), text="Canvas + Jurassic Park!!!")if __name__ == "__main__":root = Tk()frame = Frame(root, bd=2, relief=SUNKEN)frame.pack(fill=BOTH, expand=1)canvas = Canvas(frame, bd=0)canvas.grid(row=0, column=0, sticky=N+S+E+W)#adding the imagefile = filedialog.askopenfilename(parent=root, initialdir="F:/",title='Choose an image.')imgtk = ImageTk.PhotoImage(Image.open(file))canvas.create_image(0, 0, image=imgtk, anchor="nw")#mouseclick eventcanvas.bind("<Button 1>", draw_text)root.mainloop()
https://en.xdnf.cn/q/118903.html

Related Q&A

Google Cloud Storage: __init__() got an unexpected keyword argument total_size

I am developping a tool to transcribe interviews for a contract I have. For that I develop a code with the following flow:After input validation, the audio file (in m4a) is converted to wav and stored …

Selenium, Intercept HTTP Request?

Using selenium 4.12 in Python, how can I intercept an HTTP request to see what its body or headers look like? Please Note, that Im not asking for code but rather for resources/ideas of different or su…

Flask server returns 404 on localhost:5000 w/ Twilio

Im following this guide (Python Quickstart: Replying to SMS and MMS Messages) to try and set up a flask server, but when I try to connect to http://localhost:5000 I get a 404 error. I can ping 127.0.0.…

printing values and keys from a dictionary in a specific format (python)

I have this dictionary (name and grade):d1 = {a: 1, b: 2, c: 3}and I have to print it like this:|a | 1 | C | |b | 2 | B | |c | 3 | …

stdscr.getstr() ignore keys, just string

I just need convert entered text(bytes) to string. But if i on cyrillic press Backspace and some character, python throw me this error:UnicodeDecodeError: utf-8 codec cant decode byte 0xd0 in position …

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers?

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers? How should the initialization be done?line = [0] * 4 matrix = [line, line, line, line]

Creating a Data Pipeline to BigQuery Using Cloud Functions and Cloud Scheduler

I am trying to build a Data Pipeline that will download the data from this website and push it to a BigQuery Table. def OH_Data_Pipeline(trigger=Yes):if trigger==Yes:import pandas as pdimport pandas_gb…

Matching several string matches from lists and making a new row for each match

I have a data frame with text in one of the columns and I am using regex formatted strings to see if I can find any matches from three lists. However, when there are multiple matches from list 1, I wan…

Join and format array of objects in Python

I want to join and format values and array of objects to a string in python. Is there any way for me to do that?url = "https://google.com", search = "thai food", search_res = [{&q…

Copying text from file to specified Excel column [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…