fix: image alpha error
This commit is contained in:
@@ -25,6 +25,38 @@ class ImageProcessor:
|
||||
"""
|
||||
self.padding_ratio = padding_ratio or settings.image_padding_ratio
|
||||
|
||||
def _convert_to_bgr(self, pil_image: Image.Image) -> np.ndarray:
|
||||
"""Convert PIL Image to BGR numpy array, handling alpha channel.
|
||||
|
||||
Args:
|
||||
pil_image: PIL Image object.
|
||||
|
||||
Returns:
|
||||
Image as numpy array in BGR format.
|
||||
"""
|
||||
# Handle RGBA images (PNG with transparency)
|
||||
if pil_image.mode == "RGBA":
|
||||
# Create white background and paste image on top
|
||||
background = Image.new("RGB", pil_image.size, (255, 255, 255))
|
||||
background.paste(pil_image, mask=pil_image.split()[3]) # Use alpha as mask
|
||||
pil_image = background
|
||||
elif pil_image.mode == "LA":
|
||||
# Grayscale with alpha
|
||||
background = Image.new("L", pil_image.size, 255)
|
||||
background.paste(pil_image, mask=pil_image.split()[1])
|
||||
pil_image = background.convert("RGB")
|
||||
elif pil_image.mode == "P":
|
||||
# Palette mode, may have transparency
|
||||
pil_image = pil_image.convert("RGBA")
|
||||
background = Image.new("RGB", pil_image.size, (255, 255, 255))
|
||||
background.paste(pil_image, mask=pil_image.split()[3])
|
||||
pil_image = background
|
||||
elif pil_image.mode != "RGB":
|
||||
# Convert other modes to RGB
|
||||
pil_image = pil_image.convert("RGB")
|
||||
|
||||
return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
|
||||
|
||||
def load_image_from_url(self, url: str) -> np.ndarray:
|
||||
"""Load image from URL.
|
||||
|
||||
@@ -40,8 +72,8 @@ class ImageProcessor:
|
||||
try:
|
||||
with urlopen(url, timeout=30) as response:
|
||||
image_data = response.read()
|
||||
image = Image.open(io.BytesIO(image_data))
|
||||
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
||||
pil_image = Image.open(io.BytesIO(image_data))
|
||||
return self._convert_to_bgr(pil_image)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to load image from URL: {e}") from e
|
||||
|
||||
@@ -63,8 +95,8 @@ class ImageProcessor:
|
||||
base64_str = base64_str.split(",", 1)[1]
|
||||
|
||||
image_data = base64.b64decode(base64_str)
|
||||
image = Image.open(io.BytesIO(image_data))
|
||||
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
||||
pil_image = Image.open(io.BytesIO(image_data))
|
||||
return self._convert_to_bgr(pil_image)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to decode base64 image: {e}") from e
|
||||
|
||||
|
||||
Reference in New Issue
Block a user