Convert FBX files to ASCII <-> BINARY in Python

In any directory, All fbx files ASCII format or BINARY format There was a time when I wanted to convert all at once, so I tried it with python fbx sdk.

environment

FBX Python Bindings

Refer to the official documentation and put the FBX Python Bindings into your environment. Installing Python FBX (2020.0.1)

By the way, if you want to see the latest version at that time, It seems that you can get it by going as follows. https://www.autodesk.com/products/fbx/overview -> GET FBX SDK -> FBX Python Bindings

Convert

FBX file format conversion It seems that you can do it like this.

I was allowed to refer to this

Convert any fbx file format


from fbx import FbxManager
from fbx import FbxScene
from fbx import FbxImporter
from fbx import FbxExporter

FBX_MANAGER = FbxManager.Create()

def _get_file_fomrat(format_name):
    io_plugin_registry = FBX_MANAGER.GetIOPluginRegistry()
    for format_id in range(io_plugin_registry.GetWriterFormatCount()):
        if io_plugin_registry.WriterIsFBX(format_id):
            desc = io_plugin_registry.GetWriterFormatDescription(format_id)
            if format_name in desc:
                return format_id
    # Default format is auto
    return -1

def _convert(path, file_format_id):
    scene = FbxScene.Create(FBX_MANAGER, "")
    importer = FbxImporter.Create(FBX_MANAGER, "")
    importer.Initialize(path, -1)
    importer.Import(scene)
    importer.Destroy()
    exporter = FbxExporter.Create(FBX_MANAGER, "")
    exporter.Initialize(path, file_format_id)
    exporter.Export(scene)
    exporter.Destroy()
    scene.Destroy()

#Convert the target fbx file to binary
_convert('target_fbx_file_path', _get_file_fomrat('binary'))
#Convert the target fbx file to ASCII
_convert('target_fbx_file_path', _get_file_fomrat('ascii'))

Before conversion, check if the target is binary format

It's useless to convert to the same format, so Try to exclude conversions to the same format as you want.

Here seems to be unofficial but in binary format Since the header information is listed, I will refer to it.

Check if the optional fbx file is in binary format


FBX_BINARY_SIGNATURE = b"Kaydara FBX Binary  \x00\x1A\x00"
FBX_BINARY_SIGNATURE_LENGTH = len(FBX_BINARY_SIGNATURE)

def _is_binary_fbx(path):
    with open(path, 'rb') as file:
        return file.read(FBX_BINARY_SIGNATURE_LENGTH) == FBX_BINARY_SIGNATURE
    return False

Since the first 23 bytes are fixed binary data, The files are read as much as necessary and compared.

If you put this judgment at the beginning of the conversion method, Only files that are different from the desired format will be converted.

def _convert(path, file_format_id, required_binary):
    if _is_binary_fbx(path) != required_binary:
        scene = FbxScene.Create(FBX_MANAGER, "")
        importer = FbxImporter.Create(FBX_MANAGER, "")
        importer.Initialize(path, -1)
        importer.Import(scene)
        importer.Destroy()
        exporter = FbxExporter.Create(FBX_MANAGER, "")
        exporter.Initialize(path, file_format_id)
        exporter.Export(scene)
        exporter.Destroy()
        scene.Destroy()

Speed up with multiple processes

Converting 1fbx as 1 job Parallelize conversions on a file-by-file basis I will try to speed it up.

Use concurrent.futures.ProcessPoolExecutor. python 3.x series is required.

Parallelize and speed up


import concurrent.futures

with concurrent.futures.ProcessPoolExecutor() as executor:
    executor.submit(_convert, 'target_fbx_file_path', _get_file_fomrat('ascii'), false)

Walk

I want to target everything in any directory, so os.walk.

import os
import sys

with concurrent.futures.ProcessPoolExecutor() as executor:
    file_format_id = _get_file_fomrat('binary')
    for root, _dirs, files in os.walk('target_directory_path'):
        for filename in files:
            if filename.endswith('.fbx'):
                path = os.path.join(root, filename)
                executor.submit(_convert, path, file_format_id, true)

I think this made batch conversion possible a little faster.

Specify the FBX File Version of the output file

The converted file depends on the version of FBX SDK you are using, It can be specified as follows.

from fbx import FbxSceneRenamer

# FBXVersion:Become 7500
exporter.SetFileExportVersion('FBX201600', FbxSceneRenamer.eNone)
# FBXVersion:Become 7200
exporter.SetFileExportVersion('FBX201200', FbxSceneRenamer.eNone)

The version that can be specified is Defined in fbxio.h FBX_xxxx_xx_COMPATIBLE type character string.

Summary

In summary, it looks like the one uploaded below. https://github.com/yassy0413/fbx-file-utility-python/blob/master/fbx_file_format_utility.py

Recommended Posts

Convert FBX files to ASCII <-> BINARY in Python
How to convert floating point numbers to binary numbers in Python
Convert markdown to PDF in Python
Convert images passed to Jason Statham-like in Python to ASCII art
Convert psd file to png in Python
Convert HEIC files to PNG files with Python
Convert from Markdown to HTML in Python
Convert absolute URLs to relative URLs in Python
Convert files written in python etc. to pdf with syntax highlighting
Read big endian binary in Python and convert it to ndarray
Convert PDFs to images in bulk with Python
Summary of how to import files in Python 3
Binary search in Python
Convert UTF-8 CSV files to read in Excel
I made a script in python to convert .md files to Scrapbox format
How to get the files in the [Python] folder
Batch convert PSD files in directory to PDF
Convert exponential notation float to str in Python
Binary search in Python (binary search)
Convert cubic mesh code to WKT in Python
Convert timezoned date and time to Unixtime in Python2.7
Convert jupyter notebook .ipynb files to python executable .py files
How to convert / restore a string with [] in python
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
Convert NumPy array "ndarray" to lilt in Python [tolist ()]
Convert CIDR notation netmask to dotted decimal notation in Python
Convert the image in .zip to PDF with Python
Convert callback-style asynchronous API to async / await in Python
How to download files from Selenium in Python in Chrome
How to add page numbers to PDF files (in Python)
Convert / return class object to JSON format in Python
[Python] Created a method to convert radix in 1 second
Convert Webpay Entity type to Dict type (recursively in Python)
Convert hexadecimal string to binary
To flush stdout in Python
Convert numpy int64 to python int
[Python] Convert list to Pandas [Pandas]
Login to website in Python
Binary search in Python / C ++
Algorithm in Python (binary search)
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Convert CIDR notation in Python
Speech to speech in python [text to speech]
How to develop in Python
Convert python 3.x code to python 2.x
Post to Slack in Python
[R] [Python] Memo to read multiple csv files in multiple zip files
Batch convert all xlsx files in the folder to CSV files
Allow Python to select strings in input files from folders
Convert Excel file to text in Python for diff purposes
Transpose CSV files in Python Part 1
Write a binary search in Python
[Python] How to do PCA in Python
Save the binary file in Python
How to collect images in Python
How to use SQLite in Python
Manipulate files and folders in Python
Handling of JSON files in Python
Download Google Drive files in Python
Workflow to convert formula (image) to python