在图片上插入文字,python
insert text on image, python
我的项目是关于加载图像的,当我点击一个按钮时,图像中会出现一个文本区域,我可以在上面写文本,然后保存写在图像上的文本和图像。为此,我使用了 tkinter
但我将图像设置为背景并添加了一个文本框 (text widget
) 并输入了文本,但显然我无法保存该图像(设置为背景的图像) 和上面写的文字。我尝试使用 PIL
但我没有找到我要找的东西。
这是我使用 tkinter
的代码:
from tkinter import *
from PIL import ImageTk
import cv2
#root = Tk()
image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape
print(width_1)
print(height_1)
canvas = Canvas(width =height_1, height = width_1, bg = 'blue')
canvas.pack(expand = 1, fill = BOTH)
img = ImageTk.PhotoImage(file = "New_refImg.png")
canvas.create_image(0, 0, image = img, anchor = NW)
#Add text
entry = Entry(canvas, width=12)
entry.pack(side=BOTTOM,padx=43,pady=height_1-130) # "side" position button
def onok():
x= entry.get().split('x')
print(x)
Button(canvas, text='OK', command=onok).pack(side=LEFT)
mainloop()
因此,您可以在 canvas - Python: how to add text inside a canvas? - and then convert that canvas to an image for saving - How can I convert canvas content to an image?
中绘制文本
但是,我建议使用 PIL/Pillow。您可以在图像上绘制文本 - https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text. You can provide the Pillow image to ImageTk.PhotoImage directly as an argument - ImageTk.PhotoImage(im). You can naturally save the image to a file - http://pillow.readthedocs.io/en/5.2.x/reference/Image.html#PIL.Image.Image.save
我的项目是关于加载图像的,当我点击一个按钮时,图像中会出现一个文本区域,我可以在上面写文本,然后保存写在图像上的文本和图像。为此,我使用了 tkinter
但我将图像设置为背景并添加了一个文本框 (text widget
) 并输入了文本,但显然我无法保存该图像(设置为背景的图像) 和上面写的文字。我尝试使用 PIL
但我没有找到我要找的东西。
这是我使用 tkinter
的代码:
from tkinter import *
from PIL import ImageTk
import cv2
#root = Tk()
image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape
print(width_1)
print(height_1)
canvas = Canvas(width =height_1, height = width_1, bg = 'blue')
canvas.pack(expand = 1, fill = BOTH)
img = ImageTk.PhotoImage(file = "New_refImg.png")
canvas.create_image(0, 0, image = img, anchor = NW)
#Add text
entry = Entry(canvas, width=12)
entry.pack(side=BOTTOM,padx=43,pady=height_1-130) # "side" position button
def onok():
x= entry.get().split('x')
print(x)
Button(canvas, text='OK', command=onok).pack(side=LEFT)
mainloop()
因此,您可以在 canvas - Python: how to add text inside a canvas? - and then convert that canvas to an image for saving - How can I convert canvas content to an image?
中绘制文本但是,我建议使用 PIL/Pillow。您可以在图像上绘制文本 - https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text. You can provide the Pillow image to ImageTk.PhotoImage directly as an argument - ImageTk.PhotoImage(im). You can naturally save the image to a file - http://pillow.readthedocs.io/en/5.2.x/reference/Image.html#PIL.Image.Image.save