python测量图片宽度高度,交互测量脚本

import cv2
import numpy as np

image_path = r"C:\Users\18102\Downloads\bg.png"

# 读取图片(保留Alpha通道)
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
if img is None:
    print("无法读取图片,请检查路径")
    exit()

# 分离通道
if img.shape[2] == 4:
    bgr = img[:, :, :3]
    alpha = img[:, :, 3] / 255.0
    # 创建白色背景 (也可以改为 (200,200,200) 浅灰色)
    white_bg = np.full_like(bgr, 255, dtype=np.uint8)
    # 混合:前景*alpha + 背景*(1-alpha)
    blended = (bgr.astype(np.float32) * alpha[:, :, np.newaxis] + 
               white_bg.astype(np.float32) * (1 - alpha[:, :, np.newaxis]))
    display_img = blended.astype(np.uint8)
else:
    display_img = img  # 无透明通道,直接显示

# 可选:显示棋盘格辅助背景(更专业)
# 这里提供棋盘格生成函数,如果需要可注释掉上面的白色,启用下面代码
def create_checkerboard(width, height, square=20, color1=(200,200,200), color2=(255,255,255)):
    board = np.zeros((height, width, 3), dtype=np.uint8)
    for y in range(height):
        for x in range(width):
            if (x // square + y // square) % 2 == 0:
                board[y, x] = color1
            else:
                board[y, x] = color2
    return board

# 如果要用棋盘格背景,取消注释以下4行,并注释掉上面的白色背景代码:
# checker = create_checkerboard(img.shape[1], img.shape[0])
# checker_bgr = checker.astype(np.float32)
# blended = (bgr.astype(np.float32) * alpha[:, :, np.newaxis] + 
#            checker_bgr * (1 - alpha[:, :, np.newaxis]))
# display_img = blended.astype(np.uint8)

clone = display_img.copy()
points = []

def click_event(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        points.append((x, y))
        cv2.circle(clone, (x, y), 5, (0, 0, 255), -1)  # 红色点更醒目
        cv2.putText(clone, f"({x},{y})", (x+10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,255), 2)
        cv2.imshow("Image", clone)
        print(f"已记录点: ({x}, {y})")
        if len(points) == 2:
            x1, y1 = points[0]
            x2, y2 = points[1]
            left = min(x1, x2)
            top = min(y1, y2)
            right = max(x1, x2)
            bottom = max(y1, y2)
            width = right - left
            height = bottom - top
            print("\n========== 测量结果 ==========")
            print(f"左上角: ({left}, {top})")
            print(f"右下角: ({right}, {bottom})")
            print(f"宽度: {width}, 高度: {height}")
            print(f"SCREEN_RECT = ({left}, {top}, {width}, {height})")
            print("================================")
            cv2.destroyAllWindows()

cv2.namedWindow("Image", cv2.WINDOW_NORMAL)  # 可调整窗口大小
cv2.imshow("Image", clone)
cv2.setMouseCallback("Image", click_event)
print("请依次点击图片中屏幕区域的左上角和右下角(点击两下后自动退出)")
cv2.waitKey(0)
cv2.destroyAllWindows()

 

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容