繁体   English   中英

如何使用opencv python在运行时在图像上添加文本

[英]How can I add text on image at runtime using opencv python

我想在我的图像上添加文本,或者您可以在运行时说出图像上的类型。 这意味着在显示图像后运行应用程序后,通过使用鼠标指向图像,我们可以在其上键入文本。

我在opencv python中部分使用鼠标事件。 现在我想要的是,我想做两件事,

  1. 使用退格键或删除键删除文本。

  2. 显示闪烁的光标,这样就可以看到输入文本的位置。

请告诉我我该怎么做。 或者python中需要的任何东西。

这是我的代码,你可以测试它。 只需使用左键单击指向图像上的任何位置并开始输入。

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()

在我的头脑中,我将采用的方法是使用堆栈并保存发生更改的位置和值。

例如,对代码的以下修改处理退格按钮的情况。 虽然,需要进行更多测试。

基本思路是:

  1. 在打印文本之前保存旧图像的副本
  2. 区分新旧图像
  3. 找出发生变化的位置和值

按下退格键时:

  1. 从堆栈中弹出值和位置
  2. 恢复图像
  3. 更新光标位置。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM