import cv2
import numpy as np
def draw_speech_bubble(img, text, position, bubble_type):
"""
在图像上画一个带箭头的对话气泡。
:param img: 目标图像
:param text: 文本内容
:param position: 气泡左上角的坐标(x, y)
:param bubble_type: "left" 表示箭头指向左,"right"表示箭头指向右
"""
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.6
font_thickness = 2
text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness)
text_width, text_height = text_size
bubble_width = text_width + 20
bubble_height = text_height + 20
x, y = position
# 根据消息类型调整箭头和矩形位置
if bubble_type == "left":
# 矩形
cv2.rectangle(img, (x, y), (x + bubble_width, y + bubble_height), (255, 255, 255), -1)
# 箭头
pts = np.array([[x, y + bubble_height - 10],[x - 15, y + bubble_height // 2],[x, y + bubble_height // 2 + 10]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.fillPoly(img, [pts], (255,255,255))
if bubble_type == "right":
# 矩形
cv2.rectangle(img, (x - bubble_width, y), (x, y + bubble_height), (255, 255, 255), -1)
# 箭头
pts = np.array([[x, y + bubble_height - 10],[x + 15, y + bubble_height // 2],[x, y + bubble_height // 2 + 10]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.fillPoly(img, [pts], (255,255,255))
# 在矩形中加入文字
if bubble_type == "left":
cv2.putText(img, text, (x + 10, y + text_height + 10), font, font_scale, (0, 255, 0), font_thickness)
if bubble_type == "right":
cv2.putText(img, text, (x - bubble_width + 10, y + text_height + 10), font, font_scale, (0, 255, 0), font_thickness)
# 初始化聊天窗口
height, width = 500, 800
chat_window = np.ones((height, width, 3), dtype=np.uint8) * 0
# 示例消息
messages = [
("Hello! How can I help you?", 'left', (50, 50)),
("I'm looking for a Python book.", 'right', (width - 50, 100)),
("Sure, I can check our inventory.", 'left', (50, 150))
]
# 把所有消息画到聊天窗口
for message, side, position in messages:
draw_speech_bubble(chat_window, message, position, side)
# 显示窗口
cv2.imshow('Chat Box Simulation', chat_window)
cv2.imwrite("aa.jpg", chat_window)
cv2.waitKey(0)
cv2.destroyAllWindows()
opencv模拟chat对话可视化
最新推荐文章于 2024-09-20 16:09:42 发布
本文介绍了一个使用Python和OpenCV库在图像上添加对话气泡的功能,包括箭头指示方向,以及如何根据消息类型调整位置和文本显示。通过给定的函数`draw_speech_bubble`,可以模拟聊天窗口中的对话气泡效果。
摘要由CSDN通过智能技术生成