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