我正在研究一个使用Tensorflow Keras的二值图像分割问题。面具是灰度的,图像是RGB的。我需要将灰度掩码转换为二进制文件,并将它们存储在Numpy数组中。以下是守则:
from tensorflow.keras.preprocessing.image import load_img,ImageDataGenerator
from skimage.transform import resize
import os
from tqdm import tqdm
im_height,im_width = 256,256
threshold = 150
ids_test = next(os.walk("data/test/image"))[2] # list of names all images in the given path
print("No. of images = ", len(ids_test))
X_ts = np.zeros((len(ids_test), im_height, im_width, 3), dtype=np.float32)
Y_ts = np.zeros((len(ids_test), im_height, im_width, 1), dtype=np.float32)
for n, id_ in tqdm(enumerate(ids_test), total=len(ids_test)):
img = load_img("data/test/image/"+id_,
color_mode = "rgb")
x_img = img_to_array(img)
x_img = resize(x_img, (im_height, im_width,3),
mode = 'constant', preserve_range = True)
# Load masks
mask = img_to_array(load_img("data/test/label/"+id_,
color_mode = "grayscale")) #grayscale
binarized = 1.0 * (mask > threshold)
mask = resize(binarized, (im_height,im_width,1),
mode = 'constant', preserve_range = True)
# Save images
X_ts[n] = x_img/255.0
Y_ts[n] = mask
发布于 2022-11-09 14:27:18
找到了解决我问题的方法。在经验评估之后,我设定了一个全局阈值,然后对图像进行阈值化。对发布的代码进行编辑。
发布于 2022-11-09 14:29:46
您可以在numpy (熊猫.)中使用比较操作很容易地将数字数组转换为布尔数组。
array = np.random.random(5)
binary_array = array < 0.5
print(array)
print(binary_array)
这导致:
[0.57145399 0.20060058 0.13103848 0.89899815 0.45459504]
[False True True False True]
您可以轻松地检查数组的numpy类型:
print(binary_array.dtype)
bool
如果阈值为th
,则array > th
将使用布尔dtype将数组的所有值转换为true If > th
和false if <= th
。
https://stackoverflow.com/questions/74375192
复制相似问题