蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实际解码图表和视听片段

PYTHONWindows CPython 3.12.14、Pillow 13.0.0、FFmpeg 7.1、eSpeak NG、PocketSphinx 5.0.4 与 Edge。video_lab.py
video_lab.py155 行
"""Measure a local PNG and decode a time-aligned video and audio fixture."""
from importlib.metadata import version
from math import pi,sin,sqrt
from pathlib import Path
import re
import struct
import subprocess
import sys
import wave

from imageio_ffmpeg import get_ffmpeg_exe
from PIL import Image,ImageDraw

from lab_tools import run_exercise


SIZE=(96,64)
BAR_COLOR=(28,104,156)
CENTERS=(60,160,260)


def run_ffmpeg(*arguments):
    return subprocess.run([get_ffmpeg_exe(),"-hide_banner","-nostdin",*map(str,arguments)],
                          capture_output=True,encoding=None,timeout=25,check=True)


def chart(path,heights):
    image=Image.new("RGB",(320,160),"white")
    draw=ImageDraw.Draw(image)
    for x,height in zip(CENTERS,heights,strict=True):
        draw.rectangle((x-15,130-height,x+15,129),fill=BAR_COLOR)
        draw.text((x-10,135),str(x),fill="black")
    draw.line((20,130,300,130),fill="black")
    image.save(path)


def measure_chart(path):
    with Image.open(path) as image:
        if image.format!="PNG" or image.size!=(320,160):
            raise ValueError("unexpected chart fixture")
        rgb=image.convert("RGB")
        return [sum(rgb.getpixel((x,y))==BAR_COLOR for y in range(36,130)) for x in CENTERS]


def assess(heights,limit):
    return {"bars":heights,"threshold":limit,"over_limit":[index+1 for index,value in enumerate(heights) if value>limit]}


def build_video(root):
    width,height=SIZE
    frames=[]
    for index in range(8):
        image=Image.new("RGB",SIZE,(220,220,220))
        center=16 if index<4 else 56
        ImageDraw.Draw(image).rectangle((center-8,24,center+7,39),fill=(200,20,20))
        frames.append(image.tobytes())
    raw=root/"frames.rgb"
    raw.write_bytes(b"".join(frames))
    tone=root/"timeline.wav"
    pcm=[0]*16000+[round(11000*sin(2*pi*440*i/16000)) for i in range(16000)]
    with wave.open(str(tone),"wb") as audio:
        audio.setparams((1,2,16000,0,"NONE","not compressed"))
        audio.writeframes(struct.pack("<"+"h"*len(pcm),*pcm))
    target=root/"timeline.mp4"
    run_ffmpeg("-loglevel","error","-y","-f","rawvideo","-pixel_format","rgb24","-video_size",
               f"{width}x{height}","-framerate","4","-i",raw,"-i",tone,"-c:v","libx264",
               "-threads","1","-pix_fmt","yuv420p","-c:a","aac","-map_metadata","-1","-movflags","+faststart",target)
    return target


def decode_video(path):
    width,height=SIZE
    data=run_ffmpeg("-loglevel","error","-i",path,"-map","0:v:0","-f","rawvideo","-pix_fmt","rgb24","-").stdout
    size=width*height*3
    assert len(data)%size==0
    centers=[]
    for offset in range(0,len(data),size):
        frame=Image.frombytes("RGB",SIZE,data[offset:offset+size])
        points=[x for x in range(width) if (pixel:=frame.getpixel((x,32)))[0]>140 and max(pixel[1:])<90]
        assert points
        centers.append(round(sum(points)/len(points)))
    timing=run_ffmpeg("-i",path,"-map","0:v:0","-vf","showinfo","-f","null","-").stderr.decode(errors="replace")
    stamps=[float(value) for value in re.findall(r"\bn:\s*\d+\s+pts:\s*\d+\s+pts_time:([0-9.]+)",timing)]
    assert len(centers)==len(stamps)
    return centers,stamps


def audio_windows(path):
    data=run_ffmpeg("-loglevel","error","-i",path,"-map","0:a:0","-ac","1","-ar","16000","-f","s16le","-").stdout
    samples=[value for value, in struct.iter_unpack("<h",data)]
    def rms(start,end):
        segment=samples[round(start*16000):round(end*16000)]
        return sqrt(sum(sample*sample for sample in segment)/len(segment))
    return rms(0.1,0.8),rms(1.2,1.8)


def exercise(checks,root,export=None):
    expect=checks.expect
    image=root/"harbor-bars.png"
    chart(image,[24,48,72])
    actual=measure_chart(image)
    expect("media_chart_pixels",[24,48,72],"Decode actual PNG pixels at three declared bar centers",
           [24,48,72],actual)
    expect("media_mixed_threshold",{"question":"bars strictly higher than 48","threshold":48},
           "Combine image measurements with a threshold and retain the evidence values",
           {"bars":[24,48,72],"threshold":48,"over_limit":[3]},assess(actual,48))
    changed=root/"changed.png"
    chart(changed,[24,60,72])
    expect("media_image_change",[24,60,72],"Read a changed input image and recompute the same task",
           [2,3],assess(measure_chart(changed),48)["over_limit"])
    doc=root/"document-preview.png"
    screenshot=Image.new("RGB",(320,160),"white")
    draw=ImageDraw.Draw(screenshot)
    draw.text((20,20),"Dock log A7",fill="black")
    draw.rectangle((18,54,301,132),outline="black",width=2)
    draw.line((150,54,150,132),fill="black",width=2)
    draw.text((22,63),"Reading",fill="black")
    draw.text((165,63),"40",fill="black")
    screenshot.save(doc)
    with Image.open(doc) as page:
        top=page.crop((20,20,160,46))
        table=page.crop((18,54,302,133))
        actual_regions=[list(top.size),list(table.size),top.convert("L").getextrema()[0]<255,
                        table.getpixel((0,0))==(0,0,0)]
    expect("media_document_regions","self-authored raster document","Separate title and table regions without claiming OCR",
           [[140,26],[284,79],True,True],actual_regions)

    clip=build_video(root)
    positions,stamps=decode_video(clip)
    expect("media_video_timestamps",{"frames":8,"fps":4},"Decode actual frame positions and presentation timestamps",
           [[16]*4+[56]*4,[0,0.25,0.5,0.75,1,1.25,1.5,1.75]],[positions,stamps])
    uniform=[[stamps[i],positions[i]] for i in range(0,len(stamps),2)]
    changes=[[stamps[i],positions[i]] for i in range(1,len(stamps)) if abs(positions[i]-positions[i-1])>=20]
    expect("media_video_sampling","uniform every two frames and threshold change",
           "Compare sampled positions and identify the first large marker movement",
           [[[0,16],[0.5,16],[1,56],[1.5,56]],[[1,56]]],[uniform,changes])
    quiet,loud=audio_windows(clip)
    expect("media_video_audio_alignment","before and after the marker switches at 1 second",
           "Decode the actual audio track and compare RMS windows on the same timeline",
           [True,True],[quiet<200,loud>5000])
    expect("media_video_runtime","installed codecs and wrapper","Record native FFmpeg and Pillow versions",
           ["0.6.0","13.0.0",True],[version("imageio-ffmpeg"),version("Pillow"),
             run_ffmpeg("-version").stdout.startswith(b"ffmpeg version ")])
    if export is not None:
        for path in (image,doc,clip):
            (export/path.name).write_bytes(path.read_bytes())


if __name__=="__main__":
    if len(sys.argv)==3 and sys.argv[1]=="--export":
        output=Path(sys.argv[2])
        run_exercise(lambda checks,root:exercise(checks,root,output))
    else:
        run_exercise(exercise)
本例需在 Windows CPython 3.12.14、Pillow 13.0.0、FFmpeg 7.1、eSpeak NG、PocketSphinx 5.0.4 与 Edge。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPython 3.12.14、Pillow 13.0.0、FFmpeg 7.1、eSpeak NG、PocketSphinx 5.0.4 与 Edge。

入口文件:projects/ai-agent-multimodal-native/video_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 video_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPython 3.12.14、Pillow 13.0.0、FFmpeg 7.1、eSpeak NG、PocketSphinx 5.0.4 与 Edge。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3093.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习