You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过鼠标选择图像中的文本并正确计算百分比数值

如何通过鼠标选择图像中的文本并正确计算百分比数值

看起来你想要实现的是用鼠标在图像上框选对应文本的矩形区域,然后输出该区域相对图像整体尺寸的百分比参数对吧?我帮你修改现有的OpenCV代码,让它能输出你需要的top、bottom、left、right百分比数值:

首先先明确一下参数的计算逻辑(和你给出的示例完全对应):

  • top:所选区域顶部到图像顶部的距离 ÷ 图像总高度
  • bottom:图像底部到所选区域底部的距离 ÷ 图像总高度
  • left:所选区域左边缘到图像左边缘的距离 ÷ 图像总宽度
  • right:图像右边缘到所选区域右边缘的距离 ÷ 图像总宽度

下面是修改后的完整代码,我已经调整了逻辑,加入了百分比计算,并且输出格式和你需要的完全一致:

import cv2

class BoundingBoxWidget(object):
    def __init__(self):
        # 替换成你的目标图像路径
        self.original_image = cv2.imread('1.jpg')
        self.clone = self.original_image.copy()
        # 获取图像的宽高,作为百分比计算的基准
        self.img_height, self.img_width = self.original_image.shape[:2]

        cv2.namedWindow('image')
        cv2.setMouseCallback('image', self.extract_coordinates)

        # 存储选框的起始/结束坐标
        self.image_coordinates = []

    def extract_coordinates(self, event, x, y, flags, parameters):
        # 左键点击时记录选框起始坐标
        if event == cv2.EVENT_LBUTTONDOWN:
            self.image_coordinates = [(x, y)]

        # 左键松开时记录结束坐标,计算并输出百分比参数
        elif event == cv2.EVENT_LBUTTONUP:
            self.image_coordinates.append((x, y))
            # 处理用户从任意方向拖拽选框的情况,确保坐标逻辑正确
            start_x, start_y = self.image_coordinates[0]
            end_x, end_y = self.image_coordinates[1]
            top_y = min(start_y, end_y)
            bottom_y = max(start_y, end_y)
            left_x = min(start_x, end_x)
            right_x = max(start_x, end_x)

            # 计算百分比数值
            top = top_y / self.img_height
            bottom = (self.img_height - bottom_y) / self.img_height
            left = left_x / self.img_width
            right = (self.img_width - right_x) / self.img_width

            # 按照要求的格式输出结果
            print(f'top : {top}')
            print(f'bottom : {bottom}')
            print(f'left : {left}')
            print(f'right : {right}')

            # 在图像上绘制选框,方便查看
            cv2.rectangle(self.clone, (left_x, top_y), (right_x, bottom_y), (36,255,12), 2)
            cv2.imshow("image", self.clone) 

        # 右键点击重置图像,清除已绘制的选框
        elif event == cv2.EVENT_RBUTTONDOWN:
            self.clone = self.original_image.copy()

    def show_image(self):
        return self.clone

if __name__ == '__main__':
    boundingbox_widget = BoundingBoxWidget()
    while True:
        cv2.imshow('image', boundingbox_widget.show_image())
        key = cv2.waitKey(1)

        # 按q键退出程序
        if key == ord('q'):
            cv2.destroyAllWindows()
            exit(1)

使用说明:

  1. 把代码里的'1.jpg'替换成你实际要处理的图像路径
  2. 运行代码后,在弹出的图像窗口中用鼠标拖拽框选文本区域
  3. 松开左键后,控制台会自动输出四个百分比参数
  4. 右键点击可以重置图像,清除已绘制的选框
  5. 按键盘上的q键可以退出程序

备注:内容来源于stack exchange,提问作者Oussama Gamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:34:30