DeepForest调试记录

DeepForest 树检测

在原本安装好 cudatoolkit 11.3.1 对应版本pytorch以及python version 3.9 环境中,执行:
2022-01-26 22:23

conda install deepforest albumentations -c conda-forge

该命令下载了 deepforest-1.2.0

使用新数据集重新训练模型 [官方给出demo]

#load the modules
import os
import time
import cv2
import numpy as np
from deepforest import main 
from deepforest import get_data
from deepforest import utilities
from deepforest import preprocess
from PIL import Image
import rasterio
import matplotlib.pyplot as plt
# convert hand annotations from xml into retinanet format
# The get_data function is only needed when fetching sample package data
YELL_xml = get_data("2019_YELL_2_528000_4978000_image_crop2.xml")
annotation = utilities.xml_to_annotations(YELL_xml)
annotation.head()

# load the image file corresponding to the annotaion file
YELL_train = get_data("2019_YELL_2_528000_4978000_image_crop2.png")
image_path = os.path.dirname(YELL_train)
# Write converted dataframe to file. Saved alongside the images
annotation.to_csv(os.path.join(image_path,"train_example.csv"), index=False)

# prepare training data and valid data 

#Find annotation path
annotation_path = os.path.join(image_path,"train_example.csv")
# crop images will save in a newly created directory
# os.mkdir(os.getcwd(),'train_data_folder')
crop_dir = os.path.join(os.getcwd(),'train_data_folder')
train_annotations= preprocess.split_raster(path_to_raster=YELL_train,
                                 annotations_file=annotation_path,
                                 base_dir=crop_dir,
                                 patch_size=400,
                                 patch_overlap=0.05)

# Split image crops into training and test. Normally these would be different tiles! Just as an example.
image_paths = train_annotations.image_path.unique()
# split 25% validation annotation
valid_paths = np.random.choice(image_paths, int(len(image_paths)*0.25) )
valid_annotations = train_annotations.loc[train_annotations.image_path.isin(valid_paths)]
train_annotations = train_annotations.loc[~train_annotations.image_path.isin(valid_paths)]

# View output
train_annotations.head()
print("There are {} training crown annotations".format(train_annotations.shape[0]))
print("There are {} test crown annotations".format(valid_annotations.shape[0]))

# save to file and create the file dir
annotations_file= os.path.join(crop_dir,"train.csv")
validation_file= os.path.join(crop_dir,"valid.csv")
# Write window annotations file without a header row, same location as the "base_dir" above.
train_annotations.to_csv(annotations_file,index=False)
valid_annotations.to_csv(validation_file,index=False)

# print(annotations_file)

# initial the model and change the corresponding config file
m = main.deepforest()
m.config['gpus'] = '-1' #move to GPU and use all the GPU resources
m.config["train"]["csv_file"] = annotations_file
m.config["train"]["root_dir"] = os.path.dirname(annotations_file)
m.config["score_thresh"] = 0.4
m.config["train"]['epochs'] = 2
m.config["validation"]["csv_file"] = validation_file
m.config["validation"]["root_dir"] = os.path.dirname(validation_file)
# create a pytorch lighting trainer used to training 
m.create_trainer()
# load the lastest release model 
m.use_release()

print("data ok")

start_time = time.time()
m.trainer.fit(m)
print(f"--- Training on GPU: {(time.time() - start_time):.2f} seconds ---")

print()
print(annotations_file)
print()

# annotations_file='/home/pikapikaq/Desktop/TreeHeight/test/1.png'
# annotations_file='/home/pikapikaq/anaconda3/envs/workspace/lib/python3.9/site-packages/deepforest/data/OSBS_029.csv'

# save the prediction result to a prediction folder
save_dir = os.path.join(os.getcwd(),'pred_result')
try:
  os.mkdir(save_dir)
except FileExistsError:
  pass
results = m.evaluate(annotations_file, os.path.dirname(annotations_file),iou_threshold = 0.4, savedir= save_dir)

# csv_file = '/home/pikapikaq/Desktop/TreeHeight/DeepTree/train_data_folder/2019_YELL_2_528000_4978000_image_crop2_5.png'#'/home/pikapikaq/Desktop/TreeHeight/DeepTree/data/1.jpeg' #'/home/pikapikaq/anaconda3/envs/workspace/lib/python3.9/site-packages/deepforest/data/OSBS_029.tif'
# img=cv2.imread(csv_file)
# img = img.astype(np.float32)/255
# #print(img.dtype)
# # print(img)
# df = m.predict_image(image=img,return_plot=True)#root_dir = os.path.dirname(csv_file))
# print(df)

# csv_file = '/home/pikapikaq/anaconda3/envs/workspace/lib/python3.9/site-packages/deepforest/data/OSBS_029.csv'
# df = m.predict_file(csv_file, root_dir = os.path.dirname(csv_file))
# print(df)

# csv_file = '/home/pikapikaq/Desktop/TreeHeight/DeepTree/pic/OSBS_029.tif' #'/home/pikapikaq/Desktop/TreeHeight/DeepTree/data/1.jpeg'
# img=Image.open(csv_file)

# img_arr = np.array(img)
# img_arr = img_arr.astype(np.float32)/255
# print(img_arr.shape) # uint8
# print(img_arr.dtype)

# df = m.predict_image(image=img_arr,return_plot=True) # 
# print(df)

# raster = '/home/pikapikaq/Desktop/TreeHeight/DeepTree/data/1.jpeg'# get_data("2019_YELL_2_528000_4978000_image_crop2.png")
# # '/home/pikapikaq/Desktop/TreeHeight/DeepTree/data/1.jpeg'
# src = rasterio.open(raster)
# #s = DatasetReader(path, driver=driver, sharing=sharing, **kwargs)
# print(src.read().shape) # #(3, 2472, 2299)

# predicted_boxes =m.predict_tile(raster_path = raster,
#                                         patch_size = 300,
#                                         patch_overlap = 0.5,
#                                         return_plot = True)
# plt.imshow(predicted_boxes[:,:,::-1])
# plt.show()

# print(predicted_boxes)

运行Demo时 出现报错:

KeyError                                  Traceback (most recent call last)

[<ipython-input-42-0501e4367b85>](https://localhost:8080/#) in <module>()
      1 start_time = time.time()
      2 
----> 3 m.trainer.fit(m)
      4 
      5 print(f"--- Training on CPU: {(time.time() - start_time):.2f} seconds ---")

16 frames

[/usr/local/lib/python3.7/dist-packages/deepforest/main.py](https://localhost:8080/#) in load_dataset(self, csv_file, root_dir, augment, shuffle, batch_size, train)
    167                                  transforms=self.transforms(augment=augment),
    168                                  label_dict=self.label_dict,
--> 169                                  preload_images=self.config["train"]["preload_images"])
    170 
    171         data_loader = torch.utils.data.DataLoader(

KeyError: 'preload_images'

通过讨论区get到,需要更新到最新的版本,执行:

pip install deepforest --upgrade

The version 1.2.1 has no error.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 要安装Python的DeepForest库,您可以使用以下命令: ``` pip install deepforest ``` 这将使用pip包管理器自动下载和安装DeepForest库及其依赖项。请确保您的计算机已经安装了Python和pip。 ### 回答2: DeepForest是一个Python库,用于训练和应用基于深度学习的物体检测模型。这个库能够快速地训练大规模数据集,如地理空间数据和遥感图像。在实践中,DeepForest已经被证明是一个非常有用的工具,因此,很多程序员都在使用它。下面是安装DeepForest的步骤: 1.安装Anaconda或Python:DeepForest需要Python 3.6或更高版本。建议安装Anaconda,因为它提供了很多常见的数据科学库。 2.安装PyTorch:DeepForest是基于PyTorch实现的,因此需要安装PyTorch。可以在官方网站上下载最新的版本,或者使用Anaconda的命令行界面安装:conda install pytorch-cpu -c pytorch。 3.安装gdal:DeepForest需要GDAL库来读取地理空间数据。可以从GDAL官方网站上下载并安装最新的版本,或者使用Anaconda来安装:conda install gdal。 4.安装DeepForest:可以使用pip来安装DeepForest:pip install deepforest 安装完成后,可以使用以下命令测试DeepForest是否正确安装: import deepforest model = deepforest.deepforest() 如果不出错,说明DeepForest已经成功安装。 总之,安装DeepForest库非常简单,只需要按照以上步骤执行即可。值得注意的是,DeepForest的训练和测试需要大量的计算资源,因此在使用时需要注意计算机的配置。 ### 回答3: DeepForest是一个开源的深度学习库,能够在高分辨率的航拍影像上进行对象识别和定位。Python是我们常用的编程语言之一,我们可以通过安装Python中的pip工具,来完成DeepForest库的安装。以下是具体步骤: 1. 安装Python 如果您的计算机上还没有安装Python,请先前往Python官方网站下载并完成安装。请确保您的Python版本是3.6或更高版本。 2. 安装pip 在Windows中,可以打开cmd运行以下命令来安装pip: ```python python -m ensurepip –-default-pip ``` Linux/Mac用户可以通过终端命令行运行以下命令来安装pip: ```bash sudo apt update sudo apt install python3-pip ``` 3. 安装DeepForest库 打开命令行终端,输入以下命令来安装DeepForest库: ```python pip install deepforest ``` 安装过程中,pip会自动下载所需的依赖库和模块,并安装DeepForest库。 4. 测试DeepForest库 安装完成后,在命令行中输入以下代码,测试DeepForest库是否安装成功。 ```python import deepforest deepforest.demo() ``` 如果您看到了一张示例图像和检测结果,说明DeepForest库已安装完成。 以上为Python安装DeepForest库的一般过程,由于系统和软件版本等原因可能会有所不同,请根据您的系统和软件版本做出相应的修改。同时,由于DeepForest库需要进行大量的运算,建议在计算机配置较高的电脑上安装使用,以保证运行效果和体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值