首页 > 解决方案 > 如何从 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))

在此处输入图像描述

请,关于如何解决这个问题的任何想法?谢谢

标签: pythondeep-learningimage-segmentationunity3d-unetfast-ai

解决方案


我觉得预测没​​问题。你期待这样的事情吗?

预测结果

此结果基于您发布的预测图像。

要检查事情进展如何,试试这个:

 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)

基于 fast.ai 文档

关于您的预测结果,它是基于您的类值的图像。如果您从该图像中获取 (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)

此致!


推荐阅读