MinAI - Về trang chủ
Lý thuyết
6/1335 phút
Đang tải...

Image Editing và Inpainting

Chỉnh sửa hình ảnh với AI - inpainting, outpainting, background removal

0

🎯 Mục tiêu bài học

TB5 min

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

1

🔍 Editing Capabilities

TB5 min
Diagram
Đang vẽ diagram...

Checkpoint

Bạn đã nắm được các capability chính của AI image editing chưa?

2

🎨 DALL-E Editing và Inpainting

TB5 min

DALL-E Editing

python.py
1from openai import OpenAI
2
3client = OpenAI()
4
5# Edit with DALL-E
6response = client.images.edit(
7 model="dall-e-2",
8 image=open("original.png", "rb"),
9 mask=open("mask.png", "rb"), # White = area to edit
10 prompt="A beautiful garden with flowers",
11 n=1,
12 size="1024x1024"
13)
14
15edited_url = response.data[0].url

Inpainting với Stable Diffusion

python.py
1from diffusers import StableDiffusionXLInpaintPipeline
2from PIL import Image
3import torch
4
5pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
6 "stabilityai/stable-diffusion-xl-base-1.0",
7 torch_dtype=torch.float16
8)
9pipe = pipe.to("cuda")
10
11image = Image.open("photo.png").resize((1024, 1024))
12mask = Image.open("mask.png").resize((1024, 1024))
13
14result = 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.9
21).images[0]
22
23result.save("edited.png")

Checkpoint

Bạn đã hiểu cách sử dụng mask image để kiểm soát vùng inpainting chưa?

3

🛠️ Tạo Mask

TB5 min

Manual Mask

python.py
1from PIL import Image, ImageDraw
2
3# Tao mask trang (area can edit)
4mask = Image.new("RGB", (1024, 1024), "black")
5draw = ImageDraw.Draw(mask)
6# Ve vung can edit mau trang
7draw.rectangle([200, 200, 800, 800], fill="white")
8mask.save("mask.png")

AI-powered Mask (SAM)

python.py
1# Segment Anything Model
2from segment_anything import SamPredictor, sam_model_registry
3
4sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h.pth")
5predictor = SamPredictor(sam)
6
7predictor.set_image(image_array)
8
9# Click point to select object
10masks, scores, logits = predictor.predict(
11 point_coords=[[500, 500]],
12 point_labels=[1], # 1 = foreground
13 multimask_output=True
14)

Checkpoint

Bạn đã biết cách tạo mask thủ công và tự động với Segment Anything Model chưa?

4

🎨 Background Removal

TB5 min
python.py
1from rembg import remove
2from PIL import Image
3
4# Remove background
5input_image = Image.open("photo.png")
6output = remove(input_image)
7output.save("no_background.png")
8
9# Replace background
10background = Image.open("new_bg.png").resize(output.size)
11background.paste(output, mask=output.split()[3]) # Use alpha channel
12background.save("new_photo.png")

Checkpoint

Bạn đã thử remove và replace background với rembg chưa?

5

⚡ Super Resolution

TB5 min
python.py
1from diffusers import StableDiffusionUpscalePipeline
2
3upscaler = StableDiffusionUpscalePipeline.from_pretrained(
4 "stabilityai/stable-diffusion-x4-upscaler",
5 torch_dtype=torch.float16
6)
7upscaler = upscaler.to("cuda")
8
9low_res = Image.open("small_image.png")
10
11upscaled = upscaler(
12 prompt="high quality, detailed, sharp",
13 image=low_res
14).images[0]
15
16upscaled.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?

6

📐 Outpainting

TB5 min
python.py
1# Mo rong hinh anh ra ngoai boundaries
2from PIL import Image
3
4original = Image.open("photo.png")
5w, h = original.size
6
7# Tao canvas lon hon
8canvas = Image.new("RGB", (w * 2, h), "white")
9canvas.paste(original, (w // 2, 0))
10
11# Tao mask cho phan can generate
12mask = Image.new("RGB", (w * 2, h), "white")
13mask.paste(Image.new("RGB", (w, h), "black"), (w // 2, 0))
14
15# Inpaint phan trang
16result = pipe(
17 prompt="seamless landscape extension, same style and lighting",
18 image=canvas,
19 mask_image=mask,
20 guidance_scale=7.5
21).images[0]

Checkpoint

Bạn đã hiểu kỹ thuật outpainting để mở rộng hình ảnh ra ngoài boundaries chưa?

7

💻 Batch Editing Pipeline

TB5 min
python.py
1import os
2from pathlib import Path
3
4def 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}")
12
13# Batch background removal
14batch_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?

8

🎯 Tổng kết

TB5 min

Bài tập thực hành

Hands-on Exercise
  1. Inpaint để thay đổi object trong ảnh
  2. Remove và replace background
  3. Upscale ảnh chất lượng thấp
  4. Build batch editing pipeline

Challenge: Tạo product photo editor (remove bg + add shadow + new bg)

Câu hỏi tự kiểm tra

  1. 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ế?
  2. Mask image đóng vai trò gì trong quá trình inpainting và làm sao tạo mask chính xác?
  3. 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ả?
  4. 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.


🚀 Bài tiếp theo

ControlNet va Style Transfer →