Spaces:
Runtime error
Runtime error
from PIL import Image, ImageFilter | |
import numpy as np | |
def erode(image, iterations=1): | |
# モルフォロジー操作のためのカーネルを定義 | |
kernel = np.array([[0, 1, 0], | |
[1, 1, 1], | |
[0, 1, 0]], dtype=np.uint8) | |
image_np = np.array(image) | |
for _ in range(iterations): | |
eroded_image = np.zeros_like(image_np) | |
for i in range(1, image_np.shape[0] - 1): | |
for j in range(1, image_np.shape[1] - 1): | |
region = image_np[i-1:i+2, j-1:j+2] | |
eroded_image[i, j] = np.min(region + (1 - kernel) * 255) | |
image_np = eroded_image | |
return Image.fromarray(image_np.astype(np.uint8)) | |
def convert_non_white_to_black(image): | |
# 画像をNumPy配列に変換 | |
image_np = np.array(image) | |
# 完全に白でないピクセルをすべて黒にする | |
#image_np[image_np < 250] = 0 | |
image_np[image_np > 200] = 255 | |
# NumPy配列を画像に変換 | |
return Image.fromarray(image_np) | |
def adjust_transparency(image): | |
# 画像を読み込み、グレースケールに変換 | |
image.save("tmp.png") | |
image = image.convert('L') | |
image = convert_non_white_to_black(image) | |
image = image.filter(ImageFilter.SMOOTH) | |
result = Image.new('RGBA', image.size) | |
for x in range(image.width): | |
for y in range(image.height): | |
# グレースケール値を取得 | |
gray = image.getpixel((x, y)) | |
alpha = 255 | |
# 透明度の設定 | |
if gray == 0: | |
alpha = 0 # 完全に透明 | |
else: | |
alpha = 255-gray # 完全に不透明 | |
# 新しい画像にピクセルを設定 | |
result.putpixel((x, y), (0, 0, 0, alpha)) | |
return result | |
def remove_bg(image): | |
image = adjust_transparency(image) |