AtthalaricNero commited on
Commit ·
c6e0e2d
1
Parent(s): abdbea3
Implement background removal using GrabCut algorithm in preprocessing pipeline
Browse files
app.py
CHANGED
|
@@ -57,12 +57,48 @@ def extract_lbp_features(gray_img, P=8, R=1, method="uniform"):
|
|
| 57 |
return hist
|
| 58 |
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
def preprocessing_pipeline(pil_img):
|
| 61 |
img = np.array(pil_img)
|
| 62 |
|
| 63 |
# ubah format dari RGBA menjadi RGB
|
| 64 |
if img.shape[-1] == 4:
|
| 65 |
img = img[:, :, :3]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
img_float = img.astype(np.float32) / 255.0
|
| 68 |
img_uint8 = (img_float * 255).astype(np.uint8)
|
|
|
|
| 57 |
return hist
|
| 58 |
|
| 59 |
|
| 60 |
+
def remove_background(img):
|
| 61 |
+
"""
|
| 62 |
+
Menghapus background gambar menggunakan GrabCut algorithm
|
| 63 |
+
"""
|
| 64 |
+
# Buat mask
|
| 65 |
+
mask = np.zeros(img.shape[:2], np.uint8)
|
| 66 |
+
|
| 67 |
+
# Inisialisasi background dan foreground models
|
| 68 |
+
bgd_model = np.zeros((1, 65), np.float64)
|
| 69 |
+
fgd_model = np.zeros((1, 65), np.float64)
|
| 70 |
+
|
| 71 |
+
# Definisikan rectangle di sekitar objek (asumsi objek di tengah)
|
| 72 |
+
height, width = img.shape[:2]
|
| 73 |
+
rect = (10, 10, width - 10, height - 10)
|
| 74 |
+
|
| 75 |
+
# Aplikasikan GrabCut
|
| 76 |
+
cv2.grabCut(img, mask, rect, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_RECT)
|
| 77 |
+
|
| 78 |
+
# Modifikasi mask: background = 0, foreground = 1
|
| 79 |
+
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
|
| 80 |
+
|
| 81 |
+
# Terapkan mask ke gambar
|
| 82 |
+
img_no_bg = img * mask2[:, :, np.newaxis]
|
| 83 |
+
|
| 84 |
+
# Ganti background dengan putih
|
| 85 |
+
img_no_bg[mask2 == 0] = [255, 255, 255]
|
| 86 |
+
|
| 87 |
+
return img_no_bg
|
| 88 |
+
|
| 89 |
+
|
| 90 |
def preprocessing_pipeline(pil_img):
|
| 91 |
img = np.array(pil_img)
|
| 92 |
|
| 93 |
# ubah format dari RGBA menjadi RGB
|
| 94 |
if img.shape[-1] == 4:
|
| 95 |
img = img[:, :, :3]
|
| 96 |
+
|
| 97 |
+
# Resize gambar menjadi 100x100
|
| 98 |
+
img = cv2.resize(img, (100, 100), interpolation=cv2.INTER_AREA)
|
| 99 |
+
|
| 100 |
+
# Hapus background
|
| 101 |
+
img = remove_background(img)
|
| 102 |
|
| 103 |
img_float = img.astype(np.float32) / 255.0
|
| 104 |
img_uint8 = (img_float * 255).astype(np.uint8)
|