[英]How can I add text on image at runtime using opencv python
I want to add text on my image or you can say type on an image at run-time. 我想在我的图像上添加文本,或者您可以在运行时说出图像上的类型。 That means after running the application when an image is displayed, by pointing using mouse on image we able to type text on it.
这意味着在显示图像后运行应用程序后,通过使用鼠标指向图像,我们可以在其上键入文本。
I did that partially using mouse event in opencv python. 我在opencv python中部分使用鼠标事件。 Now what I want is, I want to do two things,
现在我想要的是,我想做两件事,
Delete the text using backspace or delete key. 使用退格键或删除键删除文本。
Show the blinking cursor, so one can see where text is getting typed. 显示闪烁的光标,这样就可以看到输入文本的位置。
Please tell me how can I do that. 请告诉我我该怎么做。 or anything alse is needed for that in python.
或者python中需要的任何东西。
here is my code you can test it. 这是我的代码,你可以测试它。 Just point any where on image using left click and start typing.
只需使用左键单击指向图像上的任何位置并开始输入。
xi, yi = -1,-1 # set default position
def take_posi(event, x, y,flags, param):
global xi, yi
if event == cv2.EVENT_FLAG_LBUTTON:
xi, yi = x, y #get the position where you want to type
img = cv2.imread('watch.jpg')
cv2.namedWindow('Watch')
cv2.setMouseCallback('Watch',take_posi)
font = cv2.FONT_HERSHEY_SIMPLEX
i = 10
while(1):
cv2.imshow('Watch',img)
k = cv2.waitKey(33)
if k==27: # Esc key to stop
break
elif k==-1: # normally -1 returned,so don't print it
continue
else:
print (k) # else print its value
cv2.putText(img, chr(k), (xi, yi), font, 1, (0, 255, 0), 1, cv2.LINE_AA)
xi+=15 #increment cursor
cv2.waitKey(0)
cv2.destroyAllWindows()
Off the top of my head the approach I would take would be to use stack and save locations and values where the changes have occurred. 在我的头脑中,我将采用的方法是使用堆栈并保存发生更改的位置和值。
For example, the following modification to your code handles the case of the backspace button. 例如,对代码的以下修改处理退格按钮的情况。 Although, more testing is required.
虽然,需要进行更多测试。
Basic idea is: 基本思路是:
When backspace is pressed: 按下退格键时:
Code 码
from collections import deque # import double ended queue
xi, yi = -1, -1 # set default position
def take_posi(event, x, y, flags, param):
global xi, yi
if event == cv2.EVENT_FLAG_LBUTTON:
xi, yi = x, y # get the position where you want to type
stack = deque() # create stack to keep track of overwritten values
img = cv2.imread('watch.jpg')
cv2.namedWindow('Watch')
cv2.setMouseCallback('Watch', take_posi)
font = cv2.FONT_HERSHEY_SIMPLEX
i = 10
while True:
cv2.imshow('Watch', img)
k = cv2.waitKey(33)
if k == 27: # Esc key to stop
break
elif k == -1: # normally -1 returned,so don't print it
continue
elif k == 8: # backspace
if stack:
coords, vals = stack.pop()
img[coords] = vals
xi -= 15
else:
old_img = img.copy()
cv2.putText(img, chr(k), (xi, yi), font, 1, (255, 0, 0), 1, cv2.LINE_AA)
coords = np.nonzero(old_img - img)
stack.append((coords, old_img[coords]))
xi += 15 # increment cursor
cv2.waitKey(0)
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.