200字
python绿幕抠图
2025-12-13
2026-04-01

仅处理绿幕素材,其他的不支持。导出格式为lua

#由--王者巅峰--制作,请勿删除此注释。
from PIL import Image
import os

# ================= 配置区 =================
FILE_PREFIX = "Image"   # 图片前缀
FILE_EXT = ".jpg"       # 图片后缀
TARGET_WIDTH = 80      # 动画宽度 (控制大小)
BLOCK_ID = 669          # 方块ID 
BLOCK_DATA = 3          # 方块数据
# =========================================

def process_image(image_path):
    try:
        img = Image.open(image_path)
        # 强制转换为 RGB 避免通道错误
        img = img.convert("RGB")
        w, h = img.size
        scale = TARGET_WIDTH / w
        new_height = int(h * scale)
        img = img.resize((TARGET_WIDTH, new_height), Image.Resampling.NEAREST)
        
        width, height = img.size
        coord_list = []
        
        for y in range(height):
            for x in range(width):
                r, g, b = img.getpixel((x, y))
                
                is_green_bg = (g > 150) and (r < 120) and (b < 120)
                if not is_green_bg:
                    
                    game_x = x
                    game_y = height - 1 - y
                    game_z = 0 
                    coord_str = f"{game_x},{game_y},{game_z},{BLOCK_ID},{BLOCK_DATA}"
                    coord_list.append(coord_str)
        
        # 用分号连接
        return ";".join(coord_list)
    except Exception as e:
        print(f"处理图片 {image_path} 出错: {e}")
        return ""

def main():
    script_dir = os.path.dirname(os.path.abspath(__file__))
    lua_table_lines = []
    
    # Lua 表头
    lua_table_lines.append("local buildingFrames = {")
    
    i = 1
    while True:
        # 寻找图片 Image1.jpg, Image2.jpg ...
        filename = f"{FILE_PREFIX}{i}{FILE_EXT}"
        file_path = os.path.join(script_dir, filename)
        
        if not os.path.exists(file_path):
            print(f"找不到 {filename},处理结束。共 {i-1} 帧。")
            break
            
        print(f"正在处理第 {i} 帧...")
        data = process_image(file_path)
        
        if data:
            # 写入 Lua 表格格式
            lua_table_lines.append(f'    [{i}] = "{data}",')
        else:
            # 防止空帧报错
            lua_table_lines.append(f'    [{i}] = "",')
            
        i += 1
        
    lua_table_lines.append("}")
    #lua_table_lines.append(f"local totalFrames = {i-1}")

    # 保存文件
    output_path = os.path.join(script_dir, "lua_strict_data.txt")
    with open(output_path, "w", encoding="utf-8") as f:
        f.write("\n".join(lua_table_lines))
        
    print(f"生成完毕!请打开 {output_path} 复制数据。")

if __name__ == "__main__":
    main()

lua区域脚本:

python绿幕抠图
作者
站长
发表于
2025-12-13

评论