python - 如何从 unet_learner (fastai) 获得正确的输出预测?
问题描述
拜托,我正在做一个图像分割项目,我使用了 fastai 库(特别是 unet_learner)。我已经训练了我的模型,这很好,这是我的代码(在训练阶段):
#codes = np.loadtxt('codes.txt', dtype=str)
codes = np.array(['bg', 'edge'], dtype='<U4')# bg= background
get_y_fn = lambda x: path_lbl/f'{x.stem}{x.suffix}'
# fastai codes
data = (SegmentationItemList.from_folder(path_img)
.split_by_rand_pct()
.label_from_func(get_y_fn, classes=codes)
#.add_test_folder()
#.transform(get_transforms(), tfm_y=True, size=384)
.databunch(bs=2,path=dataset) # bs = mimi-patch size
.normalize(imagenet_stats))
learn = unet_learner(data, models.resnet34, wd=1e-2)
learn.lr_find() # find learning rate
learn.recorder.plot() # plot learning rate graph
lr = 1e-02 # pick a lr
learn.fit_one_cycle(3, slice(lr), pct_start=0.3) # train model ---- epochs=3
learn.unfreeze() # unfreeze all layers
# find and plot lr again
learn.lr_find()
learn.recorder.plot()
learn.fit_one_cycle(10, slice(lr/400, lr/4), pct_start=0.3)
learn.save('model-stage-1') # save model
learn.load('model-stage-1');
learn.export()
我的问题是,当我尝试使用经过训练的模型进行预测时,输出始终是黑色图像。下面是预测阶段的代码:
img = open_image('/content/generated_samples_masks/545.png')
prediction = learn.predict(img)
prediction[0].show(figsize=(8,8))
请,关于如何解决这个问题的任何想法?谢谢
解决方案
我觉得预测没问题。你期待这样的事情吗?
此结果基于您发布的预测图像。
要检查事情进展如何,试试这个:
interp = SegmentationInterpretation.from_learner(learn)
mean_cm, single_img_cm = interp._generate_confusion()
df = interp._plot_intersect_cm(mean_cm, "Mean of Ratio of Intersection given
True Label")
i = 0 #Some image index
df = interp._plot_intersect_cm(single_img_cm[i], f"Ratio of Intersection given True Label, Image:{i}")
interp.show_xyz(i)
关于您的预测结果,它是基于您的类值的图像。如果您从该图像中获取 (r,g,b) 值,则您有(r, g, b) == 0
背景和(r, g, b) == 1
边缘。如果你有更多的类,下一个将是 as(r, g, b) == 2
等等。
所以你可以给你的预测结果上色。我是使用 OpenCV 完成的,如下所示:
frame = cv2.imread("yourPredictionHere.png",1)
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
for x in range(384): #width based on the size of your image.
for y in range(384): #height based on the size of your image.
b, g, r = frame[x, y]
if (b, g, r) == (0,0,0): #background
frame[x, y] = (0,0,0)
elif (b, g, r) == (1,1,1): #edges
frame[x, y] = (85,85,255)
cv2.imwrite("result.png",frame)
此致!
推荐阅读
- python - 使用python去除一堆文件中的短语
- oracle - 甲骨文中的多次插入只能触发一次吗?
- arrays - 过滤一个数组,其中第一个数组中的值包含打字稿中第二个数组中的值
- php - 子菜单点击列表其他下拉列表
- sql-server - SQLCMD:我们可以在输出文件中加上双引号吗?
- php - wordpress wp_insert_post 将页面添加到菜单
- android - 如何制作类似于 Ruby <=> 的运算符(又名:spaceship)
- javascript - 如何在 GET 请求中发送 x-csrf-token?
- java - Java 错误消息。意外的类型、必需的变量、找到的值
- kubernetes-helm - 如何查看 Helm 版本中使用了哪些自定义值?