🎯 Mục tiêu bài học
AI image editing cho phép chỉnh sửa hình ảnh một cách thông minh - từ thay đổi background, xóa object, đến mở rộng hình ảnh.
Sau bài này, bạn sẽ:
✅ Thực hiện inpainting và outpainting với AI ✅ Remove và replace background tự động ✅ Sử dụng super resolution để upscale ảnh ✅ Xây dựng batch editing pipeline
🔍 Editing Capabilities
Checkpoint
Bạn đã nắm được các capability chính của AI image editing chưa?
🎨 DALL-E Editing và Inpainting
DALL-E Editing
1from openai import OpenAI23client = OpenAI()45# Edit with DALL-E6response = client.images.edit(7 model="dall-e-2",8 image=open("original.png", "rb"),9 mask=open("mask.png", "rb"), # White = area to edit10 prompt="A beautiful garden with flowers",11 n=1,12 size="1024x1024"13)1415edited_url = response.data[0].urlInpainting với Stable Diffusion
1from diffusers import StableDiffusionXLInpaintPipeline2from PIL import Image3import torch45pipe = StableDiffusionXLInpaintPipeline.from_pretrained(6 "stabilityai/stable-diffusion-xl-base-1.0",7 torch_dtype=torch.float168)9pipe = pipe.to("cuda")1011image = Image.open("photo.png").resize((1024, 1024))12mask = Image.open("mask.png").resize((1024, 1024))1314result = pipe(15 prompt="modern furniture, clean design",16 image=image,17 mask_image=mask,18 guidance_scale=7.5,19 num_inference_steps=30,20 strength=0.921).images[0]2223result.save("edited.png")Checkpoint
Bạn đã hiểu cách sử dụng mask image để kiểm soát vùng inpainting chưa?
🛠️ Tạo Mask
Manual Mask
1from PIL import Image, ImageDraw23# Tao mask trang (area can edit)4mask = Image.new("RGB", (1024, 1024), "black")5draw = ImageDraw.Draw(mask)6# Ve vung can edit mau trang7draw.rectangle([200, 200, 800, 800], fill="white")8mask.save("mask.png")AI-powered Mask (SAM)
1# Segment Anything Model2from segment_anything import SamPredictor, sam_model_registry34sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h.pth")5predictor = SamPredictor(sam)67predictor.set_image(image_array)89# Click point to select object10masks, scores, logits = predictor.predict(11 point_coords=[[500, 500]],12 point_labels=[1], # 1 = foreground13 multimask_output=True14)Checkpoint
Bạn đã biết cách tạo mask thủ công và tự động với Segment Anything Model chưa?
🎨 Background Removal
1from rembg import remove2from PIL import Image34# Remove background5input_image = Image.open("photo.png")6output = remove(input_image)7output.save("no_background.png")89# Replace background10background = Image.open("new_bg.png").resize(output.size)11background.paste(output, mask=output.split()[3]) # Use alpha channel12background.save("new_photo.png")Checkpoint
Bạn đã thử remove và replace background với rembg chưa?
⚡ Super Resolution
1from diffusers import StableDiffusionUpscalePipeline23upscaler = StableDiffusionUpscalePipeline.from_pretrained(4 "stabilityai/stable-diffusion-x4-upscaler",5 torch_dtype=torch.float166)7upscaler = upscaler.to("cuda")89low_res = Image.open("small_image.png")1011upscaled = upscaler(12 prompt="high quality, detailed, sharp",13 image=low_res14).images[0]1516upscaled.save("upscaled_4x.png")Checkpoint
Bạn đã hiểu cách sử dụng AI upscaler để tăng độ phân giải ảnh chưa?
📐 Outpainting
1# Mo rong hinh anh ra ngoai boundaries2from PIL import Image34original = Image.open("photo.png")5w, h = original.size67# Tao canvas lon hon8canvas = Image.new("RGB", (w * 2, h), "white")9canvas.paste(original, (w // 2, 0))1011# Tao mask cho phan can generate12mask = Image.new("RGB", (w * 2, h), "white")13mask.paste(Image.new("RGB", (w, h), "black"), (w // 2, 0))1415# Inpaint phan trang16result = pipe(17 prompt="seamless landscape extension, same style and lighting",18 image=canvas,19 mask_image=mask,20 guidance_scale=7.521).images[0]Checkpoint
Bạn đã hiểu kỹ thuật outpainting để mở rộng hình ảnh ra ngoài boundaries chưa?
💻 Batch Editing Pipeline
1import os2from pathlib import Path34def batch_edit(input_dir, output_dir, edit_fn):5 Path(output_dir).mkdir(exist_ok=True)6 7 for img_path in Path(input_dir).glob("*.png"):8 image = Image.open(img_path)9 edited = edit_fn(image)10 edited.save(f"{output_dir}/{img_path.name}")11 print(f"Processed: {img_path.name}")1213# Batch background removal14batch_edit("photos/", "no_bg/", lambda img: remove(img))Checkpoint
Bạn đã biết cách xây dựng batch editing pipeline để xử lý nhiều ảnh cùng lúc chưa?
🎯 Tổng kết
Bài tập thực hành
- Inpaint để thay đổi object trong ảnh
- Remove và replace background
- Upscale ảnh chất lượng thấp
- Build batch editing pipeline
Challenge: Tạo product photo editor (remove bg + add shadow + new bg)
Câu hỏi tự kiểm tra
- Inpainting và outpainting khác nhau như thế nào về kỹ thuật thực hiện và ứng dụng thực tế?
- Mask image đóng vai trò gì trong quá trình inpainting và làm sao tạo mask chính xác?
- Làm sao xây dựng batch editing pipeline để xử lý hàng loạt ảnh cùng lúc một cách hiệu quả?
- Background removal bằng AI hoạt động như thế nào và có những hạn chế gì cần lưu ý?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Image Editing va Inpainting!
Tiếp theo: Chúng ta sẽ học ControlNet và Style Transfer - kiểm soát chính xác output với pose, depth và edges.
