WY16 不要二

本文探讨了一个二维网格中放置蛋糕的问题,确保任意两块蛋糕间的欧几里得距离不等于2。通过算法实现,寻找最多可放置的蛋糕数量。

二货小易有一个W*H的网格盒子,网格的行编号为0H-1,网格的列编号为0W-1。每个格子至多可以放一块蛋糕,任意两块蛋糕的欧几里得距离不能等于2。
对于两个格子坐标(x1,y1),(x2,y2)的欧几里得距离为:
( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) ) 的算术平方根
小易想知道最多可以放多少块蛋糕在网格盒子里。
输入描述:
每组数组包含网格长宽W,H,用空格分割.(1 ≤ W、H ≤ 1000)
输出描述:
输出一个最多可以放的蛋糕数

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int w, h, res = 0;
    cin >> w >> h;
    vector<vector<int>> g;
    g.resize(w);
    for (auto &e : g)
    {
        e.resize(h, 1);
    }
    for (int i = 0; i < w; i++)
    {
        for (int j = 0; j < h; j++)
        {
            if (g[i][j] == 1)
            {
                res++;
                if (i + 2 < w) g[i + 2][j] = 0;
                if (j + 2 < h) g[i][j + 2] = 0;
            }
        }
    }
    cout << res << endl;
    return 0;
}
下面这段代码请不要缩写,完整给出:<template> <div> <!-- 触发按钮 --> <a-button type="primary" @click="showModal = true">OVLData</a-button> <!-- 弹窗 --> <a-modal title="选择 OCAP 数据" v-model:visible="showModal" @ok="handleSubmit" okText="确认" cancelText="取消" width="900" > <a-form layout="vertical"> <!-- OCAP 类型选择 --> <a-form-item label="请选择 OCAP 类型"> <a-radio-group v-model:value="selectedOcapType" @change="handleOcapChange"> <a-radio value="asml">ASML OCAP</a-radio> <a-radio value="canonduv">Canon DUV OCAP</a-radio> <a-radio value="canoni">Canon I-Line OCAP</a-radio> <a-radio value="nikonscanner">Nikon Scanner OCAP</a-radio> <a-radio value="nikonstepper">Nikon Stepper OCAP</a-radio> </a-radio-group> </a-form-item> <!-- ASML 表单 --> <div v-if="selectedOcapType === 'asml'"> <a-row :gutter="16"> <a-col :span="12"> <h4>Interfield</h4> <a-form-item label="Tx"> <a-input v-model:value="asmlData.tx" @blur="checkData(asmlData.tx)" /> </a-form-item> <a-form-item label="Ty"> <a-input v-model:value="asmlData.ty" @blur="checkData(asmlData.ty)" /> </a-form-item> <!-- 其他字段略 --> </a-col> <a-col :span="12"> <h4>Intrafield</h4> <a-form-item label="S/Rot"> <a-input v-model:value="asmlData.sr" @blur="checkData(asmlData.sr)" /> </a-form-item> <!-- 其他字段略 --> <a-form-item label="MEMS Product"> <a-checkbox v-model:checked="asmlData.mp" /> </a-form-item> </a-col> </a-row> </div> <!-- 其他 OCAP 类型表单省略,结构类似 --> </a-form> </a-modal> </div> </template> <script> export default { data() { return { showModal: false, selectedOcapType: 'asml', asmlData: { tx: '', ty: '', wr: '', wn: '', wex: '', we: '', sr: '', sm: '', ar: '', am: '', mp: false }, canonduvData: { tx: '', ty: '', wx: '', wy: '', wrx: '', wry: '', smx: '', smy: '', srx: '', sry: '' }, canoniData: { tx: '', ty: '', wx: '', wy: '', wrx: '', wry: '', sm: '', sr: '' }, nikonScannerData: { tx: '', ty: '', wx: '', wy: '', wrx: '', wry: '', sx: '', sy: '', sr: '', sk: '' }, nikonStepperData: { tx: '', ty: '', wx: '', wy: '', wrx: '', wry: '', sy: '', sr: '' } }; }, methods: { handleOcapChange() { // 可选:重置当前类型的数据 }, checkData(value) { if (!value) return; const c1 = value.charAt(0), c2 = value.charAt(1); if (c1 === '-' && c2 === '0' && value.charAt(2) !== '.') { alert("输入的数据有误,请纠正!"); return; } if (c1 === '0' && c2 !== '.' && value.length > 1) { alert("输入的数据有误,请纠正!"); return; } }, handleSubmit() { let result = ''; switch (this.selectedOcapType) { case 'asml': result = `ASML: Tx=${this.asmlData.tx}; Ty=${this.asmlData.ty}; ...`; break; case 'canonduv': result = `Canon DUV: Tx=${this.canonduvData.tx}; Ty=${this.canonduvData.ty}; ...`; break; case 'canoni': result = `Canon I-Line: Tx=${this.canoniData.tx}; Ty=${this.canoniData.ty}; ...`; break; case 'nikonscanner': result = `Nikon Scanner: ShiftX=${this.nikonScannerData.tx}; ShiftY=${this.nikonScannerData.ty}; ...`; break; case 'nikonstepper': result = `Nikon Stepper: ShiftX=${this.nikonStepperData.tx}; ShiftY=${this.nikonStepperData.ty}; ...`; break; } alert(result); this.showModal = false; } } }; </script> <style scoped> /* 保持原有样式 */ </style>
12-04
import cv2 import numpy as np import random from collections import deque import mediapipe as mp import json import os from datetime import datetime import platform import time import threading from queue import Queue from PIL import Image, ImageDraw, ImageFont import pygame.mixer # ------------------------------ # 全局队列与事件 # ------------------------------ frame_queue = Queue(maxsize=1) result_queue = Queue(maxsize=1) stop_event = threading.Event() # ------------------------------ # 动态背景视频支持 # ------------------------------ bg_video = None BG_VIDEO_PATH = "menu_bg.mp4" # 动态背景视频文件 # ------------------------------ # 初始化 Mediapipe Hands # ------------------------------ mp_hands = mp.solutions.hands mp_draw = mp.solutions.drawing_utils hands = mp_hands.Hands( static_image_mode=False, max_num_hands=2, min_detection_confidence=0.7, min_tracking_confidence=0.5 ) # ------------------------------ # 中文字体加载 # ------------------------------ def get_chinese_font(): system = platform.system() font_paths = { "Windows": ["C:/Windows/Fonts/simhei.ttf", "C:/Windows/Fonts/msyh.ttc"], "Darwin": ["/System/Library/Fonts/PingFang.ttc"], "Linux": [ "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc" ] } for path in font_paths.get(system, []): if os.path.exists(path): try: return ImageFont.truetype(path, 32) except Exception as e: print(f"⚠️ 字体加载失败: {path}, 错误: {e}") return None try: CHINESE_FONT = get_chinese_font() except ImportError: print("警告: 未安装Pillow,中文可能无法正常显示。请运行: pip install pillow") CHINESE_FONT = None def put_chinese_text(image, text, position=None, color=(255, 255, 255), font_size=30, center_region=None): if CHINESE_FONT is None: if position: cv2.putText(image, text, position, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2) return image try: pil_img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(pil_img) try: if hasattr(CHINESE_FONT, 'path'): font = ImageFont.truetype(CHINESE_FONT.path, font_size) else: font = ImageFont.load_default() except: font = ImageFont.load_default() bbox = draw.textbbox((0, 0), text, font=font) tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1] if center_region: x1, y1, x2, y2 = center_region fx = x1 + (x2 - x1 - tw) // 2 fy = y1 + (y2 - y1 - th) // 2 elif position: fx, fy = position else: fx = fy = 0 draw.text((fx, fy), text, fill=tuple(color), font=font) return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR) except Exception as e: print("中文绘制失败:", e) if position: cv2.putText(image, text, position, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2) return image # ------------------------------ # 音频系统(pygame.mixer) # ------------------------------ pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=512) _sound_cache = {} _volume = 0.5 _muted = False def _load_sound(file): if file in _sound_cache: return _sound_cache[file] if os.path.exists(file): try: sound = pygame.mixer.Sound(file) sound.set_volume(_volume) _sound_cache[file] = sound return sound except Exception as e: print(f"❌ 加载音效失败: {file}, 错误: {e}") else: print(f"⚠️ 音效文件未找到: {file}") return None def play_sound(sound_file): if not _muted: sound = _load_sound(sound_file) if sound: sound.play() def play_bgm(bgm_file, loop=-1): if _muted or not os.path.exists(bgm_file): return try: pygame.mixer.music.load(bgm_file) pygame.mixer.music.set_volume(_volume) pygame.mixer.music.play(loop) except Exception as e: print(f"❌ 播放 BGM 失败: {e}") def stop_bgm(): pygame.mixer.music.stop() def toggle_mute(): global _muted _muted = not _muted vol = 0.0 if _muted else _volume pygame.mixer.music.set_volume(vol) for s in _sound_cache.values(): if s: s.set_volume(vol) return _muted # ------------------------------ # 排行榜管理 # ------------------------------ RANKING_FILE = "snake_ranking.json" MAX_RECORDS = 100 def load_ranking(): if not os.path.exists(RANKING_FILE): return [] try: with open(RANKING_FILE, 'r', encoding='utf-8') as f: data = json.load(f) seen = set() unique_data = [] for item in data: key = (item.get('score', 0), item.get('timestamp', '')) if key not in seen: seen.add(key) unique_data.append(item) return sorted(unique_data, key=lambda x: x['score'], reverse=True)[:MAX_RECORDS] except Exception as e: print("加载排行榜失败:", e) return [] def save_best_score(score, mode="single"): ranking = load_ranking() current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") ranking.append({"score": score, "timestamp": current_time, "mode": mode}) seen = set() unique_ranking = [] for r in ranking: key = (r['score'], r['timestamp']) if key not in seen: seen.add(key) unique_ranking.append(r) unique_ranking = sorted(unique_ranking, key=lambda x: x['score'], reverse=True)[:MAX_RECORDS] try: with open(RANKING_FILE, 'w', encoding='utf-8') as f: json.dump(unique_ranking, f, indent=2, ensure_ascii=False) except Exception as e: print("保存失败:", e) def show_ranking(): ranking = load_ranking() frame = np.zeros((720, 1280, 3), dtype=np.uint8) h, w = frame.shape[:2] for y in range(h): c = 30 + y // 20 frame[y, :] = [c // 2, c // 3, c] frame = put_chinese_text(frame, "🏆 历史排行榜 🏆", center_region=(0, 40, w, 120), color=(255, 255, 100), font_size=60) frame = put_chinese_text(frame, "按任意键返回主菜单", center_region=(0, h - 80, w, h), color=(200, 200, 255), font_size=30) if not ranking: frame = put_chinese_text(frame, "暂无记录", center_region=(0, h//2 - 20, w, h//2 + 20), color=(150, 150, 150), font_size=40) else: start_y = 140 for i, record in enumerate(ranking[:50]): score = record['score'] timestamp = record['timestamp'] mode = record.get('mode', 'unknown') mode_text = "单人" if mode == "single" else "双人" if mode == "dual" else "未知" text = f"{i+1:2d}. {score:4d} 分 — {timestamp} [{mode_text}]" color = (255, 255, 255) if i % 2 == 0 else (220, 220, 220) frame = put_chinese_text(frame, text, (w//2 - 480, start_y + i * 32), color=color, font_size=28) cv2.imshow("Hand-Controlled Snake Game", frame) cv2.waitKey(0) def clear_ranking(): frame = np.zeros((720, 1280, 3), dtype=np.uint8) h, w = frame.shape[:2] for y in range(h): frame[y, :] = [20 + y // 20, (20 + y // 20) // 2, 60] frame = put_chinese_text(frame, "⚠️ 清空所有记录?", center_region=(0, h//2 - 100, w, h//2 - 40), color=(0, 0, 255), font_size=48) frame = put_chinese_text(frame, "确定要清空吗?(Y=是, N=否)", center_region=(0, h//2 - 20, w, h//2 + 20), color=(255, 255, 255), font_size=36) frame = put_chinese_text(frame, "此操作不可撤销!", center_region=(0, h//2 + 40, w, h//2 + 80), color=(150, 150, 150), font_size=32) cv2.imshow("Hand-Controlled Snake Game", frame) while True: key = cv2.waitKey(1) & 0xFF if key in (ord('y'), ord('Y')): try: os.remove(RANKING_FILE) except: pass return True elif key in (ord('n'), ord('N'), 27): return False # ------------------------------ # 动态背景视频相关函数 # ------------------------------ def load_background_video(): """加载背景视频""" global bg_video if os.path.exists(BG_VIDEO_PATH): bg_video = cv2.VideoCapture(BG_VIDEO_PATH) bg_video.set(cv2.CAP_PROP_BUFFERSIZE, 1) print(f"✅ 成功加载背景视频: {BG_VIDEO_PATH}") else: print(f"❌ 背景视频未找到: {BG_VIDEO_PATH},将使用默认渐变背景") bg_video = None def get_background_frame(): """获取下一帧背景画面""" global bg_video if bg_video is None: return None ret, frame = bg_video.read() if not ret: bg_video.set(cv2.CAP_PROP_POS_FRAMES, 0) ret, frame = bg_video.read() if ret: frame = cv2.resize(frame, (1280, 720)) return frame return None # ------------------------------ # 主菜单界面(带动态视频背景) # ------------------------------ def show_main_menu(): global bg_video if bg_video is None: load_background_video() play_bgm("bgm.mp3") ranking = load_ranking() best_score = ranking[0]['score'] if ranking else 0 width, height = 1280, 720 btn_w, btn_h = 300, 80 cx = width // 2 btn_y_start = 220 spacing = 80 while True: bg_frame = get_background_frame() if bg_frame is not None: frame = bg_frame.copy() frame = cv2.GaussianBlur(frame, (5, 5), 0) frame = cv2.addWeighted(frame, 0.7, np.zeros_like(frame), 0, 30) else: frame = np.zeros((height, width, 3), dtype=np.uint8) for y in range(height): c = 20 + y // 20 frame[y, :] = [c, c // 2, 60] frame = put_chinese_text(frame, "🐍 手势贪吃蛇游戏 🐍", center_region=(0, 0, width, 120), color=(255, 255, 100), font_size=60) buttons = [ ("👤 单人模式", btn_y_start, (100, 0, 200), (140, 0, 240)), ("👥 双人对战", btn_y_start + spacing, (180, 0, 180), (220, 0, 220)), ("📊 查看排行榜", btn_y_start + 2*spacing, (0, 100, 200), (0, 180, 255)), ("🗑️ 清空记录", btn_y_start + 3*spacing, (60, 60, 60), (150, 150, 150)), ] for label, y, bg_color, border_color in buttons: left = cx - btn_w // 2 right = cx + btn_w // 2 top = y bottom = y + btn_h cv2.rectangle(frame, (left, top), (right, bottom), bg_color, -1) cv2.rectangle(frame, (left, top), (right, bottom), border_color, 5) frame = put_chinese_text(frame, label, center_region=(left, top, right, bottom), color=(255, 255, 255), font_size=36) tip_text = f"🏆 最高分: {best_score}|1=单人 2=双人 3=退出 4=清空 5=排行 M=静音" frame = put_chinese_text(frame, tip_text, center_region=(0, 600, width, 640), color=(200, 255, 255), font_size=24) cv2.imshow("Hand-Controlled Snake Game", frame) start_t = time.time() while time.time() - start_t < 0.1: key = cv2.waitKey(1) & 0xFF if key == ord('1'): return "single" elif key == ord('2'): return "dual" elif key == ord('3'): return "quit" elif key == ord('4'): clear_ranking() break elif key == ord('5'): show_ranking() break elif key == ord('m'): is_muted = toggle_mute() status = "🔇 已静音" if is_muted else "🔊 音效开启" help_frame = frame.copy() help_frame = put_chinese_text(help_frame, status, center_region=(0, 650, width, 690), color=(255, 255, 0), font_size=24) cv2.imshow("Hand-Controlled Snake Game", help_frame) cv2.waitKey(800) break elif key != 255: help_frame = frame.copy() help_frame = put_chinese_text(help_frame, "💡 提示: 1=单人 2=双人 3=退出 4=清空 5=排行 M=静音", center_region=(0, 650, width, 690), color=(255, 255, 0), font_size=24) cv2.imshow("Hand-Controlled Snake Game", help_frame) cv2.waitKey(1500) break # ------------------------------ # 摄像头读取线程 # ------------------------------ def capture_thread(): cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) while not stop_event.is_set(): ret, frame = cap.read() if ret: frame = cv2.flip(frame, 1) if not frame_queue.empty(): try: frame_queue.get_nowait() except: pass frame_queue.put(frame) else: time.sleep(0.01) cap.release() # ------------------------------ # 手势识别线程 # ------------------------------ def hand_thread(): while not stop_event.is_set(): if not frame_queue.empty(): frame = frame_queue.get() rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = hands.process(rgb_frame) if not result_queue.empty(): try: result_queue.get_nowait() except: pass result_queue.put((frame.copy(), results)) else: time.sleep(0.01) # ------------------------------ # 启动后台线程 # ------------------------------ load_background_video() # 👈 加载视频背景 capture_t = threading.Thread(target=capture_thread, daemon=True) hand_t = threading.Thread(target=hand_thread, daemon=True) capture_t.start() hand_t.start() # ------------------------------ # 游戏参数 # ------------------------------ width, height = 1280, 720 snake_speed = 8 food_radius = 15 food_color = (0, 255, 0) # ------------------------------ # 安全工具函数 # ------------------------------ def is_point_in_wall(x, y, walls): return any(wx <= x <= wx + ww and wy <= y <= wy + wh for (wx, wy, ww, wh) in walls) def check_wall_collision(head, walls): hx, hy = head return any(wx <= hx <= wx + ww and wy <= hy <= wy + wh for (wx, wy, ww, wh) in walls) def generate_safe_food_position(snake_bodies, walls, retries=100): all_segments = [] for body in (snake_bodies if isinstance(snake_bodies, list) else [snake_bodies]): all_segments.extend(list(body)) for _ in range(retries): x = random.randint(50, width - 50) y = random.randint(50, height - 50) pos = np.array([x, y]) if is_point_in_wall(x, y, walls): continue too_close = False for seg in all_segments: if np.linalg.norm(pos - np.array(seg)) < 30: too_close = True break if too_close: continue return [int(x), int(y)] fallback_positions = [(width - 60, height - 60), (60, height - 60), (width - 60, 60), (60, 60)] for fx, fy in fallback_positions: pos = np.array([fx, fy]) if not is_point_in_wall(fx, fy, walls): safe = True for seg in all_segments: if np.linalg.norm(pos - np.array(seg)) < 30: safe = False break if safe: return [fx, fy] return [width // 2, height // 2] def add_wall_safely(walls_list, snake_bodies, food_pos): if len(walls_list) >= 5: return walls_list all_snakes = [] for body in (snake_bodies if isinstance(snake_bodies, list) else [snake_bodies]): all_snakes.extend(list(body)) for _ in range(30): ww, wh = random.randint(40, 150), random.randint(40, 150) wx, wy = random.randint(50, width - ww - 50), random.randint(50, height - wh - 50) new_wall = (wx, wy, ww, wh) temp_walls = walls_list + [new_wall] if not is_point_in_wall(all_snakes[0][0], all_snakes[0][1], temp_walls) and \ not is_point_in_wall(food_pos[0], food_pos[1], temp_walls): walls_list.append(new_wall) break return walls_list # ------------------------------ # 绘图封装 # ------------------------------ def draw_game_elements(frame, snakes, food, walls, scores, game_over, right_hand_pos=None, left_hand_pos=None): try: for wall in walls: wx, wy, ww, wh = map(int, wall) cv2.rectangle(frame, (wx, wy), (wx + ww, wy + wh), (255, 255, 0), -1) cv2.rectangle(frame, (wx, wy), (wx + ww, wy + wh), (0, 0, 0), 3) fx, fy = map(int, food) if 0 <= fx < width and 0 <= fy < height: cv2.circle(frame, (fx, fy), food_radius, food_color, -1) s1, s2 = snakes sc1, sc2 = scores for i in range(1, len(s1)): p1, p2 = s1[i - 1], s1[i] if all(0 <= v < 10000 for v in (*p1, *p2)): cv2.line(frame, p1, p2, (0, 0, 200), 8) cv2.circle(frame, s1[0], 10, (255, 255, 255), -1) cv2.circle(frame, s1[0], 8, (0, 0, 255), -1) if len(s2) > 0: for i in range(1, len(s2)): p1, p2 = s2[i - 1], s2[i] if all(0 <= v < 10000 for v in (*p1, *p2)): cv2.line(frame, p1, p2, (200, 0, 0), 8) cv2.circle(frame, s2[0], 10, (255, 255, 255), -1) cv2.circle(frame, s2[0], 8, (255, 0, 0), -1) frame = put_chinese_text(frame, f"🔴红蛇得分: {sc1}", (20, 15), (255, 255, 255), 40) if sc2 > 0: frame = put_chinese_text(frame, f"🔵蓝蛇得分: {sc2}", (20, 60), (255, 255, 255), 40) if right_hand_pos and all(0 <= v < width for v in right_hand_pos): cv2.circle(frame, tuple(map(int, right_hand_pos)), 12, (0, 0, 255), -1) cv2.putText(frame, "R", (right_hand_pos[0] - 10, right_hand_pos[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) if left_hand_pos and all(0 <= v < width for v in left_hand_pos): cv2.circle(frame, tuple(map(int, left_hand_pos)), 12, (255, 0, 0), -1) cv2.putText(frame, "L", (left_hand_pos[0] - 10, left_hand_pos[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) except Exception as e: print("绘图异常:", e) def show_game_over_screen_dual(score1, score2): overlay = np.zeros((height, width, 3), dtype=np.uint8) cv2.rectangle(overlay, (width // 4, height // 4), (3 * width // 4, 3 * height // 4), (0, 0, 0), -1) overlay = put_chinese_text(overlay, "游戏结束", center_region=(0, height//2 - 80, width, height//2 - 20), color=(0, 0, 255), font_size=60) overlay = put_chinese_text(overlay, f"红蛇得分: {score1}", center_region=(0, height//2, width, height//2 + 40), color=(0, 0, 255), font_size=32) overlay = put_chinese_text(overlay, f"蓝蛇得分: {score2}", center_region=(0, height//2 + 40, width, height//2 + 80), color=(255, 0, 0), font_size=32) cv2.imshow("Hand-Controlled Snake Game", overlay) play_sound("game_over.wav") save_best_score(max(score1, score2), mode="dual") cv2.waitKey(800) def show_game_over_screen_single(score): overlay = np.zeros((height, width, 3), dtype=np.uint8) cv2.rectangle(overlay, (width // 4, height // 4), (3 * width // 4, 3 * height // 4), (0, 0, 0), -1) overlay = put_chinese_text(overlay, "游戏结束", center_region=(0, height//2 - 60, width, height//2 - 20), color=(0, 255, 0), font_size=60) overlay = put_chinese_text(overlay, f"你的得分: {score}", center_region=(0, height//2, width, height//2 + 40), color=(255, 255, 255), font_size=40) cv2.imshow("Hand-Controlled Snake Game", overlay) play_sound("game_over.wav") save_best_score(score, mode="single") cv2.waitKey(800) # ------------------------------ # 单人游戏循环 # ------------------------------ def run_single_player(): snake = deque([(width // 2, height // 2)]) direction = np.array([1.0, 0.0]) base_length = 3 score = 0 walls = [] food = generate_safe_food_position(snake, walls) target_pos = None game_over = False while not game_over: if not result_queue.empty(): frame, results = result_queue.get() key = cv2.waitKey(1) & 0xFF curr_target = None try: if results.multi_hand_landmarks and results.multi_handedness: for idx, hand_landmarks in enumerate(results.multi_hand_landmarks): label = results.multi_handedness[idx].classification[0].label if label == "Right": x = int(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * width) y = int(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * height) curr_target = (x, y) mp_draw.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS) if curr_target: target_pos = curr_target if target_pos is None else ( int(0.3 * curr_target[0] + 0.7 * target_pos[0]), int(0.3 * curr_target[1] + 0.7 * target_pos[1]) ) if target_pos: head = np.array(snake[0]) to_target = np.array(target_pos) - head dist = np.linalg.norm(to_target) if dist > 30: desired_dir = to_target / (dist + 1e-8) current_dir = direction / (np.linalg.norm(direction) + 1e-8) dot = np.clip(np.dot(current_dir, desired_dir), -1, 1) angle = np.arccos(dot) if angle > 0.25: w1, w2 = np.sin(angle - 0.25), np.sin(0.25) blended = (w1 * current_dir + w2 * desired_dir) / (np.sin(angle) + 1e-8) direction = blended / (np.linalg.norm(blended) + 1e-8) else: direction = desired_dir new_head = head + direction * snake_speed snake.appendleft(tuple(np.round(new_head).astype(int))) h = np.array(snake[0]) if h[0] <= 0 or h[0] >= width or h[1] <= 0 or h[1] >= height or check_wall_collision(h, walls): game_over = True for i in range(4, len(snake)): if np.linalg.norm(h - np.array(snake[i])) < 15: game_over = True break if np.linalg.norm(h - np.array(food)) < (food_radius + 10): score += 1 food = generate_safe_food_position(snake, walls) play_sound("eat.wav") if score % 5 == 0: walls = add_wall_safely(walls, snake, food) target_len = base_length + score while len(snake) > target_len: snake.pop() draw_game_elements(frame, [snake, deque()], food, walls, (score, 0), game_over, right_hand_pos=target_pos, left_hand_pos=None) cv2.imshow("Hand-Controlled Snake Game", frame) if game_over: show_game_over_screen_single(score) break if key == 27: break except Exception as e: print("单人模式异常:", e) time.sleep(0.1) else: time.sleep(0.01) # ------------------------------ # 主游戏循环 # ------------------------------ while True: action = show_main_menu() if action == "quit": break elif action == "single": run_single_player() elif action == "dual": snake1 = deque([(width // 3, height // 2)]) dir1 = np.array([1.0, 0.0]) len1 = 3 snake2 = deque([(2 * width // 3, height // 2)]) dir2 = np.array([-1.0, 0.0]) len2 = 3 score1, score2 = 0, 0 walls = [] food = generate_safe_food_position([*snake1, *snake2], walls) game_over = False target_right = None target_left = None while not game_over: if not result_queue.empty(): frame, results = result_queue.get() key = cv2.waitKey(1) & 0xFF curr_right = None curr_left = None try: if results and results.multi_hand_landmarks and results.multi_handedness: hands_info = [] for idx, hand_landmarks in enumerate(results.multi_hand_landmarks): wrist_x = hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].x x = int(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * width) y = int(hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * height) hands_info.append((wrist_x, x, y, hand_landmarks)) hands_info.sort(key=lambda x: x[0], reverse=True) for i, (_, x, y, landmarks) in enumerate(hands_info): mp_draw.draw_landmarks(frame, landmarks, mp_hands.HAND_CONNECTIONS) if i == 0: curr_right = (x, y) if i == 1: curr_left = (x, y) if curr_right: target_right = curr_right if target_right is None else ( int(0.3 * curr_right[0] + 0.7 * target_right[0]), int(0.3 * curr_right[1] + 0.7 * target_right[1])) if curr_left: target_left = curr_left if target_left is None else ( int(0.3 * curr_left[0] + 0.7 * target_left[0]), int(0.3 * curr_left[1] + 0.7 * target_left[1])) if target_right: head1 = np.array(snake1[0]) to_t = np.array(target_right) - head1 dist = np.linalg.norm(to_t) if dist > 30: desired = to_t / (dist + 1e-8) curr_dir = dir1 / (np.linalg.norm(dir1) + 1e-8) dot = np.clip(np.dot(curr_dir, desired), -1, 1) angle = np.arccos(dot) if angle > 0.25: w1, w2 = np.sin(angle - 0.25), np.sin(0.25) blended = (w1 * curr_dir + w2 * desired) / (np.sin(angle) + 1e-8) dir1 = blended / (np.linalg.norm(blended) + 1e-8) else: dir1 = desired new_head1 = head1 + dir1 * snake_speed snake1.appendleft(tuple(np.round(new_head1).astype(int))) if target_left: head2 = np.array(snake2[0]) to_t = np.array(target_left) - head2 dist = np.linalg.norm(to_t) if dist > 30: desired = to_t / (dist + 1e-8) curr_dir = dir2 / (np.linalg.norm(dir2) + 1e-8) dot = np.clip(np.dot(curr_dir, desired), -1, 1) angle = np.arccos(dot) if angle > 0.25: w1, w2 = np.sin(angle - 0.25), np.sin(0.25) blended = (w1 * curr_dir + w2 * desired) / (np.sin(angle) + 1e-8) dir2 = blended / (np.linalg.norm(blended) + 1e-8) else: dir2 = desired new_head2 = head2 + dir2 * snake_speed snake2.appendleft(tuple(np.round(new_head2).astype(int))) h1, h2 = np.array(snake1[0]), np.array(snake2[0]) if (h1[0] <= 0 or h1[0] >= width or h1[1] <= 0 or h1[1] >= height or check_wall_collision(h1, walls)): game_over = True for i in range(4, len(snake1)): if np.linalg.norm(h1 - np.array(snake1[i])) < 15: game_over = True break if (h2[0] <= 0 or h2[0] >= width or h2[1] <= 0 or h2[1] >= height or check_wall_collision(h2, walls)): game_over = True for i in range(4, len(snake2)): if np.linalg.norm(h2 - np.array(snake2[i])) < 15: game_over = True break eaten = False if np.linalg.norm(h1 - np.array(food)) < (food_radius + 10): score1 += 1 eaten = True if np.linalg.norm(h2 - np.array(food)) < (food_radius + 10): score2 += 1 eaten = True if eaten: play_sound("eat.wav") food = generate_safe_food_position([*snake1, *snake2], walls) if score1 % 5 == 0 or score2 % 5 == 0: walls = add_wall_safely(walls, [*snake1, *snake2], food) while len(snake1) > len1 + score1: snake1.pop() while len(snake2) > len2 + score2: snake2.pop() draw_game_elements(frame, [snake1, snake2], food, walls, (score1, score2), game_over, right_hand_pos=target_right, left_hand_pos=target_left) cv2.imshow("Hand-Controlled Snake Game", frame) if game_over: show_game_over_screen_dual(score1, score2) break if key == 27: break except Exception as e: print("双人模式异常:", e) time.sleep(0.1) else: time.sleep(0.01) # ------------------------------ # 释放资源 # ------------------------------ stop_event.set() time.sleep(0.5) if bg_video is not None: bg_video.release() cv2.destroyAllWindows() hands.close() stop_bgm() pygame.mixer.quit() 提高MP4视频流畅度,不要改动其他代码
11-10
Looking in indexes: https://mirror.baidu.com/pypi/simple/, https://mirrors.aliyun.com/pypi/simple/ Requirement already satisfied: opencv-python in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (4.1.1.26) Collecting dlib Downloading https://mirrors.aliyun.com/pypi/packages/28/f4/f8949b18ec1df2ef05fc2ea1d1dd82ff2d050b8704b7d0d088017315c221/dlib-20.0.0.tar.gz (3.3 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.3/3.3 MB 12.2 MB/s eta 0:00:0000:0100:01 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: matplotlib in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (2.2.3) Requirement already satisfied: pillow in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (8.2.0) Requirement already satisfied: requests in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (2.22.0) Requirement already satisfied: beautifulsoup4 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (4.11.1) Requirement already satisfied: scikit-learn in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (0.24.2) Requirement already satisfied: numpy>=1.14.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from opencv-python) (1.20.3) Requirement already satisfied: six>=1.10 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (1.16.0) Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (2.8.2) Requirement already satisfied: pytz in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (2019.3) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (3.0.9) Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from matplotlib) (1.1.0) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests) (3.0.4) Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests) (2.8) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests) (1.25.6) Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from requests) (2019.9.11) Requirement already satisfied: soupsieve>1.2 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from beautifulsoup4) (2.3.2.post1) Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from scikit-learn) (2.1.0) Requirement already satisfied: scipy>=0.19.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from scikit-learn) (1.6.3) Requirement already satisfied: joblib>=0.11 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from scikit-learn) (0.14.1) Requirement already satisfied: setuptools in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib) (56.2.0) Building wheels for collected packages: dlib Building wheel for dlib (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for dlib (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [252 lines of output] running bdist_wheel running build running build_ext Building extension for Python 3.7.4 (default, Aug 13 2019, 20:35:49) Invoking CMake setup: 'cmake /tmp/pip-install-9ool2zzu/dlib_7816ed707750450bb5cceeb2f0daf3b2/tools/python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/tmp/pip-install-9ool2zzu/dlib_7816ed707750450bb5cceeb2f0daf3b2/build/lib.linux-x86_64-cpython-37 -DPYTHON_EXECUTABLE=/opt/conda/envs/python35-paddle120-env/bin/python -DDLIB_USE_FFMPEG=OFF -DCMAKE_BUILD_TYPE=Release' -- The C compiler identification is GNU 7.5.0 -- The CXX compiler identification is GNU 7.5.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: /usr/bin/cc - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: /usr/bin/c++ - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- pybind11 v2.12.0 -- Found PythonInterp: /opt/conda/envs/python35-paddle120-env/bin/python (found suitable version "3.7.4", minimum required is "3.6") -- Found PythonLibs: /opt/conda/envs/python35-paddle120-env/lib/libpython3.7m.so -- Performing Test HAS_FLTO -- Performing Test HAS_FLTO - Success -- Using CMake version: 3.24.2 -- Compiling dlib version: 20.0.0 -- SSE4 instructions can be executed by the host processor. -- AVX instructions can be executed by the host processor. -- Enabling AVX instructions -- Performing Test CMAKE_HAVE_LIBC_PTHREAD -- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed -- Looking for pthread_create in pthreads -- Looking for pthread_create in pthreads - not found -- Looking for pthread_create in pthread -- Looking for pthread_create in pthread - found -- Found Threads: TRUE -- Found X11: /usr/include -- Looking for XOpenDisplay in /usr/lib/x86_64-linux-gnu/libX11.so;/usr/lib/x86_64-linux-gnu/libXext.so -- Looking for XOpenDisplay in /usr/lib/x86_64-linux-gnu/libX11.so;/usr/lib/x86_64-linux-gnu/libXext.so - found -- Looking for gethostbyname -- Looking for gethostbyname - found -- Looking for connect -- Looking for connect - found -- Looking for remove -- Looking for remove - found -- Looking for shmat -- Looking for shmat - found -- Looking for IceConnectionNumber in ICE -- Looking for IceConnectionNumber in ICE - found -- Found system copy of libpng: /usr/lib/x86_64-linux-gnu/libpng.so;/usr/lib/x86_64-linux-gnu/libz.so -- Found system copy of libjpeg: /usr/lib/x86_64-linux-gnu/libjpeg.so -- Found WebP: /usr/lib/x86_64-linux-gnu/libwebp.so -- System copy of libwebp is either too old or broken. Will disable WebP support. -- Searching for JPEG XL -- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1") -- Checking for modules 'libjxl;libjxl_cms;libjxl_threads' -- No package 'libjxl' found -- No package 'libjxl_cms' found -- No package 'libjxl_threads' found ***************************************************************************** *** No JPEG XL libraries found. *** *** On Ubuntu 23.04 and newer you can install them by executing *** *** sudo apt install libjxl-dev *** *** *** *** Otherwise, you can find precompiled packages here: *** *** https://github.com/libjxl/libjxl/releases *** ***************************************************************************** -- Searching for BLAS and LAPACK -- Searching for BLAS and LAPACK -- Checking for module 'cblas' -- No package 'cblas' found -- Checking for module 'lapack' -- Found lapack, version 3.10.2 -- Looking for cblas_ddot -- Looking for cblas_ddot - not found -- Looking for sys/types.h -- Looking for sys/types.h - found -- Looking for stdint.h -- Looking for stdint.h - found -- Looking for stddef.h -- Looking for stddef.h - found -- Check size of void* -- Check size of void* - done -- Found LAPACK library -- Found ATLAS BLAS library -- Looking for cblas_ddot -- Looking for cblas_ddot - found -- Looking for sgesv -- Looking for sgesv - not found -- Looking for sgesv_ -- Looking for sgesv_ - found -- Found CUDA: /usr/local/cuda (found suitable version "10.1", minimum required is "7.5") -- Looking for cuDNN install... -- Found cuDNN: /usr/lib/x86_64-linux-gnu/libcudnn.so -- Building a CUDA test project to see if your compiler is compatible with CUDA... -- Building a cuDNN test project to check if you have the right version of cuDNN installed... -- Enabling CUDA support for dlib. DLIB WILL USE CUDA, compute capabilities: 50 -- Configuring done -- Generating done -- Build files have been written to: /tmp/pip-install-9ool2zzu/dlib_7816ed707750450bb5cceeb2f0daf3b2/build/temp.linux-x86_64-cpython-37 Invoking CMake build: 'cmake --build . --config Release -- -j64' [ 1%] Building NVCC (Device) object dlib_build/CMakeFiles/dlib.dir/cuda/dlib_generated_cusolver_dlibapi.cu.o [ 2%] Building NVCC (Device) object dlib_build/CMakeFiles/dlib.dir/cuda/dlib_generated_cuda_dlib.cu.o [ 3%] Building CXX object dlib_build/CMakeFiles/dlib.dir/base64/base64_kernel_1.cpp.o [ 4%] Building CXX object dlib_build/CMakeFiles/dlib.dir/bigint/bigint_kernel_1.cpp.o [ 5%] Building CXX object dlib_build/CMakeFiles/dlib.dir/bigint/bigint_kernel_2.cpp.o [ 6%] Building CXX object dlib_build/CMakeFiles/dlib.dir/bit_stream/bit_stream_kernel_1.cpp.o [ 7%] Building CXX object dlib_build/CMakeFiles/dlib.dir/entropy_decoder/entropy_decoder_kernel_1.cpp.o [ 8%] Building CXX object dlib_build/CMakeFiles/dlib.dir/entropy_decoder/entropy_decoder_kernel_2.cpp.o [ 9%] Building CXX object dlib_build/CMakeFiles/dlib.dir/entropy_encoder/entropy_encoder_kernel_1.cpp.o [ 10%] Building CXX object dlib_build/CMakeFiles/dlib.dir/entropy_encoder/entropy_encoder_kernel_2.cpp.o [ 12%] Building CXX object dlib_build/CMakeFiles/dlib.dir/tokenizer/tokenizer_kernel_1.cpp.o [ 12%] Building CXX object dlib_build/CMakeFiles/dlib.dir/md5/md5_kernel_1.cpp.o [ 13%] Building CXX object dlib_build/CMakeFiles/dlib.dir/unicode/unicode.cpp.o [ 14%] Building CXX object dlib_build/CMakeFiles/dlib.dir/sockets/sockets_kernel_1.cpp.o [ 15%] Building CXX object dlib_build/CMakeFiles/dlib.dir/test_for_odr_violations.cpp.o [ 16%] Building CXX object dlib_build/CMakeFiles/dlib.dir/fft/fft.cpp.o [ 17%] Building CXX object dlib_build/CMakeFiles/dlib.dir/bsp/bsp.cpp.o [ 18%] Building CXX object dlib_build/CMakeFiles/dlib.dir/dir_nav/dir_nav_kernel_1.cpp.o [ 20%] Building CXX object dlib_build/CMakeFiles/dlib.dir/dir_nav/dir_nav_extensions.cpp.o [ 21%] Building CXX object dlib_build/CMakeFiles/dlib.dir/logger/extra_logger_headers.cpp.o [ 22%] Building CXX object dlib_build/CMakeFiles/dlib.dir/logger/logger_kernel_1.cpp.o [ 23%] Building CXX object dlib_build/CMakeFiles/dlib.dir/dir_nav/dir_nav_kernel_2.cpp.o [ 24%] Building CXX object dlib_build/CMakeFiles/dlib.dir/misc_api/misc_api_kernel_1.cpp.o [ 25%] Building CXX object dlib_build/CMakeFiles/dlib.dir/linker/linker_kernel_1.cpp.o [ 26%] Building CXX object dlib_build/CMakeFiles/dlib.dir/misc_api/misc_api_kernel_2.cpp.o [ 27%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/fonts.cpp.o [ 28%] Building CXX object dlib_build/CMakeFiles/dlib.dir/logger/logger_config_file.cpp.o [ 29%] Building CXX object dlib_build/CMakeFiles/dlib.dir/sockets/sockets_extensions.cpp.o [ 30%] Building CXX object dlib_build/CMakeFiles/dlib.dir/sockstreambuf/sockstreambuf_unbuffered.cpp.o [ 31%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/multithreaded_object_extension.cpp.o [ 32%] Building CXX object dlib_build/CMakeFiles/dlib.dir/sockets/sockets_kernel_2.cpp.o [ 33%] Building CXX object dlib_build/CMakeFiles/dlib.dir/server/server_kernel.cpp.o [ 35%] Building CXX object dlib_build/CMakeFiles/dlib.dir/server/server_http.cpp.o [ 35%] Building CXX object dlib_build/CMakeFiles/dlib.dir/sockstreambuf/sockstreambuf.cpp.o [ 36%] Building CXX object dlib_build/CMakeFiles/dlib.dir/server/server_iostream.cpp.o [ 37%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/thread_pool_extension.cpp.o [ 38%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/threads_kernel_2.cpp.o [ 40%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/threads_kernel_1.cpp.o [ 41%] Building CXX object dlib_build/CMakeFiles/dlib.dir/timer/timer.cpp.o [ 42%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/threads_kernel_shared.cpp.o [ 43%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/threaded_object_extension.cpp.o [ 44%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/cpu_dlib.cpp.o [ 46%] Building CXX object dlib_build/CMakeFiles/dlib.dir/stack_trace.cpp.o [ 45%] Building CXX object dlib_build/CMakeFiles/dlib.dir/threads/async.cpp.o [ 47%] Building CXX object dlib_build/CMakeFiles/dlib.dir/data_io/mnist.cpp.o [ 48%] Building CXX object dlib_build/CMakeFiles/dlib.dir/data_io/image_dataset_metadata.cpp.o [ 49%] Building CXX object dlib_build/CMakeFiles/dlib.dir/global_optimization/global_function_search.cpp.o [ 50%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/tensor_tools.cpp.o [ 51%] Building CXX object dlib_build/CMakeFiles/dlib.dir/filtering/kalman_filter.cpp.o [ 52%] Building CXX object dlib_build/CMakeFiles/dlib.dir/data_io/cifar.cpp.o [ 53%] Building CXX object dlib_build/CMakeFiles/dlib.dir/svm/auto.cpp.o [ 54%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/widgets.cpp.o [ 55%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/canvas_drawing.cpp.o [ 56%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/drawable.cpp.o [ 57%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/style.cpp.o [ 58%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_core/gui_core_kernel_1.cpp.o [ 60%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_core/gui_core_kernel_2.cpp.o [ 61%] Building CXX object dlib_build/CMakeFiles/dlib.dir/image_saver/save_png.cpp.o [ 62%] Building CXX object dlib_build/CMakeFiles/dlib.dir/gui_widgets/base_widgets.cpp.o [ 63%] Building CXX object dlib_build/CMakeFiles/dlib.dir/image_loader/png_loader.cpp.o [ 64%] Building CXX object dlib_build/CMakeFiles/dlib.dir/image_loader/jpeg_loader.cpp.o [ 66%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/gpu_data.cpp.o [ 66%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/cudnn_dlibapi.cpp.o [ 67%] Building CXX object dlib_build/CMakeFiles/dlib.dir/image_saver/save_jpeg.cpp.o [ 68%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/cublas_dlibapi.cpp.o [ 69%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/cuda_data_ptr.cpp.o [ 70%] Building CXX object dlib_build/CMakeFiles/dlib.dir/cuda/curand_dlibapi.cpp.o [ 71%] Linking CXX static library libdlib.a [ 71%] Built target dlib [ 72%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/dlib.cpp.o [ 73%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/matrix.cpp.o [ 74%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/vector.cpp.o [ 75%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/svm_c_trainer.cpp.o [ 76%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/svm_rank_trainer.cpp.o [ 77%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/decision_functions.cpp.o [ 78%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/other.cpp.o [ 80%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/basic.cpp.o [ 81%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/cca.cpp.o [ 82%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/sequence_segmenter.cpp.o [ 83%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/svm_struct.cpp.o [ 85%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/image3.cpp.o [ 85%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/image.cpp.o [ 86%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/image2.cpp.o [ 87%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/correlation_tracker.cpp.o [ 88%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/face_recognition.cpp.o [ 89%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/image4.cpp.o [ 90%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/shape_predictor.cpp.o [ 91%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/rectangles.cpp.o [ 92%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/object_detection.cpp.o [ 93%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/numpy_returns.cpp.o [ 94%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/line.cpp.o [ 95%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/cnn_face_detector.cpp.o [ 96%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/gui.cpp.o [ 97%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/global_optimization.cpp.o [ 98%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/image_dataset_metadata.cpp.o c++: internal compiler error: Killed (program cc1plus) Please submit a full bug report, with preprocessed source if appropriate. See <file:///usr/share/doc/gcc-7/README.Bugs> for instructions. CMakeFiles/_dlib_pybind11.dir/build.make:243: recipe for target 'CMakeFiles/_dlib_pybind11.dir/src/image2.cpp.o' failed make[2]: *** [CMakeFiles/_dlib_pybind11.dir/src/image2.cpp.o] Error 4 make[2]: *** Waiting for unfinished jobs.... CMakeFiles/Makefile2:117: recipe for target 'CMakeFiles/_dlib_pybind11.dir/all' failed make[1]: *** [CMakeFiles/_dlib_pybind11.dir/all] Error 2 Makefile:90: recipe for target 'all' failed make: *** [all] Error 2 Traceback (most recent call last): File "/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module> main() File "/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 262, in build_wheel metadata_directory) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/build_meta.py", line 417, in build_wheel wheel_directory, config_settings) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/build_meta.py", line 401, in _build_with_temp_dir self.run_setup() File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/build_meta.py", line 338, in run_setup exec(code, locals()) File "<string>", line 273, in <module> File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/__init__.py", line 107, in setup return distutils.core.setup(**attrs) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/core.py", line 185, in setup return run_commands(dist) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/core.py", line 201, in run_commands dist.run_commands() File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/dist.py", line 969, in run_commands self.run_command(cmd) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/dist.py", line 1234, in run_command super().run_command(command) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/dist.py", line 988, in run_command cmd_obj.run() File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/wheel/bdist_wheel.py", line 368, in run self.run_command("build") File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/cmd.py", line 318, in run_command self.distribution.run_command(command) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/dist.py", line 1234, in run_command super().run_command(command) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/dist.py", line 988, in run_command cmd_obj.run() File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/command/build.py", line 131, in run self.run_command(cmd_name) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/cmd.py", line 318, in run_command self.distribution.run_command(command) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/dist.py", line 1234, in run_command super().run_command(command) File "/tmp/pip-build-env-wy1gbu0h/overlay/lib/python3.7/site-packages/setuptools/_distutils/dist.py", line 988, in run_command cmd_obj.run() File "<string>", line 168, in run File "<string>", line 209, in build_extension File "/opt/conda/envs/python35-paddle120-env/lib/python3.7/subprocess.py", line 347, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--config', 'Release', '--', '-j64']' returned non-zero exit status 2. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for dlib Failed to build dlib ERROR: Could not build wheels for dlib, which is required to install pyproject.toml-based projects [notice] A new release of pip available: 22.1.2 -> 24.0 [notice] To update, run: pip install --upgrade pip --2025-12-29 19:03:04-- https://github.com/davisking/dlib-models/raw/master/shape_predictor_68_face_landmarks.dat.bz2 Resolving github.com (github.com)... 20.205.243.166 Connecting to github.com (github.com)|20.205.243.166|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://raw.githubusercontent.com/davisking/dlib-models/master/shape_predictor_68_face_landmarks.dat.bz2 [following] --2025-12-29 19:03:05-- https://raw.githubusercontent.com/davisking/dlib-models/master/shape_predictor_68_face_landmarks.dat.bz2 Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.111.133, 185.199.108.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.
最新发布
12-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JayceSun449

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值