Skip to main content
 首页 » 编程设计

python之使用 python 从二值图像中裁剪感兴趣区域

2024年11月24日22youxin

要求是从二值图像中裁剪出感兴趣的区域。

我需要通过移除感兴趣区域周围的额外空间来从二值图像中提取一个矩形图像。

例如: 从这个Original图片我只想要 region of interest用黄色矩形标记。

注意:黄色矩形仅供引用,不会出现在将要处理的图像中。

我尝试了以下 python 代码,但它没有提供所需的输出。

from PIL import Image 
from skimage.io import imread 
from skimage.morphology import convex_hull_image 
import numpy as np 
from matplotlib import pyplot as plt 
from skimage import io 
from skimage.color import rgb2gray 
im = imread('binaryImageEdited.png') 
plt.imshow(im) 
plt.title('input image') 
plt.show() 
# create a binary image 
im1 = 1 - rgb2gray(im) 
threshold = 0.8 
im1[im1 <= threshold] = 0 
im1[im1 > threshold] = 1 
chull = convex_hull_image(im1) 
plt.imshow(chull) 
plt.title('convex hull in the binary image') 
plt.show() 
imageBox = Image.fromarray((chull*255).astype(np.uint8)).getbbox() 
cropped = Image.fromarray(im).crop(imageBox) 
cropped.save('L_2d_cropped.png') 
plt.imshow(cropped) 
plt.show() 

谢谢。

请您参考如下方法:

由于两件事,您的图像实际上不是二进制的:

  • 首先,它有 26 种颜色,并且
  • 其次,它有一个(完全不必要的)alpha channel 。

你可以像这样修剪它:

#!/usr/bin/env python3 
 
from PIL import Image, ImageOps 
 
# Open image and ensure greysale and discard useless alpha channel 
im = Image.open("thing.png").convert('L') 
 
# Threshold and invert image as not actually binary 
thresh = im.point(lambda p: p < 64 and 255) 
 
# Get bounding box of thresholded image 
bbox1 = thresh.getbbox() 
crop1 = thresh.crop(bbox1) 
 
# Invert and crop again 
crop1n = ImageOps.invert(crop1) 
bbox2  = crop1n.getbbox() 
crop2  = crop1.crop(bbox2)  # You don't actually need this - it's just for debug 
 
# Trim original, unthresholded, uninverted image to the two bounding boxes 
result = im.crop(bbox1).crop(bbox2) 
result.save('result.png')