š Remove Backgrounds for Free with Python by Just Creating a FolderāāāWhy Donāt Operating Systems Offer This?
Operating systems like macOS, Windows, and Ubuntu are hailed as technological marvels, but have they stopped innovating in the areas we care about most? Simple tasks like removing a background from an image can become cumbersome workflows. Itās time we rethink how files are managed and automated, and no, Apple fans, this isnāt about roasting macOS ā itās about envisioning a better future for all operating systems.
When I say to people that operating systems could benefit from a lot of improvements, people usually disprove that claim. MacOS, Windows or Ubuntu are perfect depending on whom you ask.
Last time I did it I was almost cancelled by MacOS belovers. What I did I wrote on social media that:
Took my Mac to a meeting on the go, thinking I was a productivity genius. But no ā close the lid, and it goes straight to sleep. So there I am, holding it half-open like a complete fool, trying to to drop it. Apple, who thought this was a good idea?
Just for a context, on Windows I can just set it up in settings, without any need to install third party apps for one switch to disable sleep mode when closing lid. But itās not available in MacOS. What a shame!
What a shame to the community to dismiss things that could improve their favorite operating system!
The list of things that can be improved in operating systems is long, but their evolution stopped many years ago, and they either stall, go worse or innovate in areas nobody cares about.
Today Iāll show you one thing I think every operating system should handle years ago and itās surprising no-one did it so far. It may not have any sense, but the mechanism could be explored at least at some point in time in the past. Now AI could take it over, but it will also need some slick way to handle such operations.
Itās about manipulating files. We have folders right? Why not use them?
For this example letās take background removal process. Do remove background from an image, you have to open image, tap some option, tap another option, save the file, open next file. Or, select all files, upload to online service and download processed files, extract them from zip. Or you can use an app where you select apps, process them, and save. Why so hard?
Look, I have these three files:
I donāt care about apps, online services etc. I just want to remove background from them. What would I do, if I had the background removed? Iād like to preserve the images, but have new files with background removed while preserving the file names. So Iād like to have a new folder with background removed:
All I really want is to have these files in ābackground-removedā folder with backgroundsā¦ removed. Without ever exiting Windows Explorer.
How hard it can be?
Please look at this:
You may think itās some kind of magic, or I start some app in the background to do it. But actually I didnāt have to do anything in this moment for this to work.
Well, I had only to create one service that runs in the background. What it does is monitor the whole system, and when you create a āwithout backgroundā folder, it automatically removes the background from images and saves them into that folder. Voila, end of story: create a folder.
How hard does it have to be? By the way, if youāre intrigued by how Python makes such automation possible, youāll love the Python Deck Iāve created. Itās a gamified way to master Pythonās essential functions, helping you build scripts like this with ease!
You may think it has a footprint on the system, actually not, it has almost zero footprint: 97 MB while idle, 0 CPU, 0 Disk. Iām sure if someone more knowledgeable than me would improve it even further.
If we think about it, that way of handling file conversions could be brought further, to resize images, prepare images for social media, convert between formats, improve colors and so on. The sky is the limit.
But before you dive into creating your next million dollar startupĀ (asĀ aĀ gentlemanĀ IĀ wantĀ 1%Ā ofĀ profit), letās focus on one thing: operating systems could actually offer it out of the box. There are folders, there are automated operations. Why we need to use all these tedious methods and apps, services to do the simplest things? I donāt need to open a fancy app with all sorts of ads and tracking and pay so much money just to get my files converted in some pretty standard ways.
Anyways, hereās the script:
import os
import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from rembg import remove
import ctypes
import platform
class BackgroundRemovalHandler(FileSystemEventHandler):
def on_created(self, event):
"""Handle folder creation events."""
print(f"Detected event: {event.src_path} (is_directory={event.is_directory})")
if event.is_directory:
folder_name = os.path.basename(event.src_path)
if folder_name.lower() == "without background":
parent_dir = os.path.dirname(event.src_path)
print(f"'without background' folder detected at: {event.src_path}")
process_images(parent_dir, event.src_path)
def on_moved(self, event):
"""Handle folder rename events."""
print(f"Detected rename/move: {event.src_path} -> {event.dest_path}")
if event.is_directory:
folder_name = os.path.basename(event.dest_path)
if folder_name.lower() == "without background":
parent_dir = os.path.dirname(event.dest_path)
print(f"'without background' folder detected after rename at: {event.dest_path}")
process_images(parent_dir, event.dest_path)
def process_images(source_dir, target_dir):
"""
Processes all images in the source_dir and saves the background-removed versions in the target_dir.
"""
print(f"Processing images from: {source_dir} to: {target_dir}")
for filename in os.listdir(source_dir):
file_path = os.path.join(source_dir, filename)
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
print(f"Processing: {filename}")
try:
with open(file_path, 'rb') as input_file:
input_image = input_file.read()
output_image = remove(input_image)
output_path = os.path.join(target_dir, filename)
with open(output_path, 'wb') as output_file:
output_file.write(output_image)
print(f"Saved processed image: {output_path}")
except Exception as e:
print(f"Error processing {filename}: {e}")
def is_admin():
"""Check if the script is running with administrative privileges."""
if platform.system() == "Windows":
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
elif platform.system() == "Linux" or platform.system() == "Darwin":
return os.geteuid() == 0
return False
def run_as_admin():
"""Re-run the script with administrative privileges."""
if platform.system() == "Windows":
print("Restarting script with admin privileges...")
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1
)
sys.exit()
elif platform.system() == "Linux" or platform.system() == "Darwin":
print("Please run this script with sudo.")
sys.exit()
def monitor_folders(path):
"""Monitor the file system for folder creation and rename events."""
print(f"Monitoring path: {path}")
event_handler = BackgroundRemovalHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == "__main__":
if not is_admin():
run_as_admin()
try:
monitor_folders("/")
except Exception as e:
print(f"Error starting folder monitor: {e}")
100 lines of code in Python.
Idk why, but operating system manufacturers are so lazy, I donāt imagine they will come up with anything innovative these days except trying to gather as much of our private activity to train AI.
But we have Python, so we can do awesome stuff, fortunately! Hi, Iām Tom Smykowski, and Iām passionate about sharing innovative ideas, automation tips, and all things tech. If you enjoy this article, letās connect! You can find me on social media for more updates, discussions, and fun tech content. Donāt forget to subscribe to my Medium for more articles like this one ā Iād love to have you join the conversation. š
BTW. You can actually expand the script, and run it permanently in your system. Iāve tested it on Windows, and included instructions how to autostart it on itās GitHub.
The evolution of operating systems has stalled, leaving users to rely on clunky workflows or third-party apps for simple tasks. What if your OS could handle common file operations, like removing backgrounds, resizing images, or optimizing files, seamlessly and natively?
Using Python, I created a lightweight service that automates background removal with a single action: creating a folder. This article explores how such features could transform OS design and empower users to focus on creativity instead of tedious processes. And yes, this script runs smoothly with minimal system impact.
If you enjoyed this article and found it helpful or thought-provoking, Iād love your support! Give it a clap (or several if you really liked it), share it with your friends or colleagues who might appreciate a new take on operating systems, and letās start a conversation.
What features do you think OS developers are missing out on? Drop your thoughts in the comments ā Iād love to hear from you! Your engagement helps me keep creating content like this and inspires new ideas for the tech community. š