在图像上插入文本,python [英] insert text on image, python

查看:558
本文介绍了在图像上插入文本,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目是关于加载图像,当我点击一个按钮时,图像中会出现一个文本区域,我可以在其上写一个文本,然后保存写在图像和图像上的文本。为此,我使用 tkinter ,但我将图像设置为背景,并添加了一个文本框(文本小部件)和输入文本,但显然我无法保存该图像(设置为背景)和写在其上的文本。我尝试使用 PIL 但我找不到我要找的东西。
这是我的代码,使用 tkinter

My project is about loading an image and when I click on a button, a text area appears in the image, and I can write a text on it and later on save the text written on the image and the image. To do so I used tkinter but I set my image as background and I added a text box(text widget) and enter a text, but obviously I can't save that image( the one set as background) and the text written on it. I tried using PIL but i didn't find what I was looking for. This is my code using 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()


推荐答案

因此,您可以在画布中绘制文字 - Python:如何在画布中添加文本?​​ - 然后将该画布转换为图像以便保存 - 如何将画布内容转换为图像?

So, you could draw text into your 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 。您可以将Pillow图像直接作为参数提供给ImageTk.PhotoImage - ImageTk.PhotoImage(im)。您可以自然地将图像保存到文件中 - http://pillow.readthedocs.io/en/5.2.x/reference/Image.html#PIL.Image.Image.save

However, I would instead recommend using PIL/Pillow. You can draw text onto an image - 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

这篇关于在图像上插入文本,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆