Context
I'm converting a PNG sequence into a video using FFMPEG. The images are semi-transparent portraits where the background has been removed digitally.
Issue
The edge pixels of the subject are stretched all the way to the frame border, creating a fully opaque video.
Cause Analysis
The process worked fine in the previous workflow using rembg from command line however, since I started using rembg via python script using alpha_matting to obtain higher quality results, the resulting video has these issues.
The issue is present in both webm format (target) and mp4 (used for testing).
Command Used
Command used for webm is:
ffmpeg -thread_queue_size 64 -framerate 30 -i <png sequence location> -c:v libvpx -b:v 0 -crf 18 -pix_fmt yuva420p -auto-alt-ref 0 -c:a libvorbis <png output>
Throubleshooting Steps Taken
- PNG Visual inspection The PNG images have a fully transparent background as desired.
- PNG Alpha Measurement I have created a couple of python scripts to look at alpha level in pixels and confirmed that there is no subtle alpha level in the background pixels
- Exported MP4 with AE Using the native AE renderer the resulting MP4/H.265 has a black background, so not showing the stretched pixel issue
Image of the Issue
Sample PNG Image from sequence
Code Context
rembg call via API using alpha_matting seems to generate a premultiplied alpha which uses non black pixels for 0 alpha pixels.
remove(input_data, alpha_matting=True, alpha_matting_foreground_threshold=250,
alpha_matting_background_threshold=250, alpha_matting_erode_size=12)
A test using a rough RGB reset of 0-alpha pixels confirms that the images are being played with their RGB value ignoring Alpha.
def reset_alpha_pixels(img):
# Open the image file
# Process each pixel
data = list(img.getdata())
new_data = []
for item in data:
if item[3] == 0:
new_data.append((0, 0, 0, 0))
else:
new_data.append((item[0], item[1], item[2], item[3]))
# Replace the alpha value but keep the RGB
# Update the image data
img.putdata(new_data)
return img
Updates
- Added python context to make the question more relevant within SO scope.