迷失的小屋
首页
注册

11111

jzh
2025-04-22 16:23:43
import cv2
import numpy as np
from matplotlib import pyplot as plt

# 读取图片
image = cv2.imread('sucai8/hand.png')

# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 二值化处理,选择合适的阈值
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 找到轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 用for循环找到最大的轮廓的索引(即手掌轮廓)
largest_contour_index = np.argmax([cv2.contourArea(cnt) for cnt in contours])
largest_contour = contours[largest_contour_index]


# 创建滑块“epsilon”来控制 approxPolyDP 函数的 epsilon 参数
def nothing(x):
    pass


# 创建窗口
cv2.namedWindow('epsilon')

# 创建滑块,范围从0.01到0.1,初始值为0.02
cv2.createTrackbar('epsilon', 'epsilon', 0, 100, nothing)

# 等待用户调整滑块
while True:
    # 获取滑块当前值并转换为浮点数,然后除以100得到实际的epsilon值
    epsilon_val = cv2.getTrackbarPos('epsilon', 'epsilon') / 100.0
    epsilon = epsilon_val * cv2.arcLength(largest_contour, True)


    approx = cv2.approxPolyDP(largest_contour, epsilon, True)


    draw = cv2.drawContours(image.copy(), [approx], -1, (0, 0, 255), 2)


    plt.figure(figsize=(10, 8))
    plt.imshow(cv2.cvtColor(draw, cv2.COLOR_BGR2RGB))
    plt.title('Hand Contour with Polygon Approximation - epsilon 6')  # 添加名字
    plt.axis('off')
    plt.pause(0.001)

    # 按'q'键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 保存结果(可选,根据需求决定是否保存)
# cv2.imwrite('hand_contour_with_epsilon.jpg', draw)