opencv模拟chat对话可视化

本文介绍了一个使用Python和OpenCV库在图像上添加对话气泡的功能,包括箭头指示方向,以及如何根据消息类型调整位置和文本显示。通过给定的函数`draw_speech_bubble`,可以模拟聊天窗口中的对话气泡效果。
摘要由CSDN通过智能技术生成
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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值