10. 基于AR的虚拟植物种植应用

import cv2
import numpy as np
import os

# 初始化摄像头
cap = cv2.VideoCapture(0)
cv2.namedWindow("AR Virtual Gardening")

# 加载植物图像
plants = []
plant_names = ["plant1.png", "plant2.png", "plant3.png"]
for name in plant_names:
    img = cv2.imread(os.path.join("images", name), cv2.IMREAD_UNCHANGED)
    plants.append(img)

# 定义绘制函数
def overlay_image(background, overlay, x, y):
    h, w = overlay.shape[0], overlay.shape[1]
    alpha_overlay = overlay[:, :, 3] / 255.0
    alpha_background = 1.0 - alpha_overlay

    for c in range(0, 3):
        background[y:y+h, x:x+w, c] = (alpha_overlay * overlay[:, :, c] +
                                       alpha_background * background[y:y+h, x:x+w, c])

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 进行植物绘制
    overlay_image(frame, plants[0], 100, 100)
    overlay_image(frame, plants[1], 300, 100)
    overlay_image(frame, plants[2], 500, 100)

    cv2.imshow("AR Virtual Gardening", frame)

    key = cv2.waitKey(1)
    if key == 27:  # 按ESC退出
        break

cap.release()
cv2.destroyAllWindows()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.