使用pytorch应用简单变换获得二值图像
我想在将图像传递给数据加载器之前对其进行二值化,我已经创建了一个工作良好的dataset类。但是在使用pytorch应用简单变换获得二值图像,pytorch,image-preprocessing,pytorch-dataloader,Pytorch,Image Preprocessing,Pytorch Dataloader,我想在将图像传递给数据加载器之前对其进行二值化,我已经创建了一个工作良好的dataset类。但是在\uuu getitem\uuu()方法中,我想对图像设置阈值: def __getitem__(self, idx): # Open image, apply transforms and return with label img_path = os.path.join(self.dir, self.filelist[filename"])
\uuu getitem\uuu()
方法中,我想对图像设置阈值:
def __getitem__(self, idx):
# Open image, apply transforms and return with label
img_path = os.path.join(self.dir, self.filelist[filename"])
image = Image.open(img_path)
label = self.x_data.iloc[idx]["label"]
# Applying transformation to the image
if self.transforms is not None:
image = self.transforms(image)
# applying threshold here:
my_threshold = 240
image = image.point(lambda p: p < my_threshold and 255)
image = torch.tensor(image)
return image, label
因为我已经在一个PIL对象上应用了阈值,所以我需要在转换之后应用到一个张量对象,但是由于某种原因它崩溃了。有人能帮我吗?为什么不在从
PIL.Image
转换到torch.Tensor
之后应用二值化呢
类阈值变换(对象):
定义初始化(自我,thr_255):
self.thr=thr_255/255.#[0..255]灰度的输入阈值,转换为[0..1]
定义调用(self,x):
返回(x>self.thr)。到(x.dtype)#不更改数据类型
完成此转换后,只需添加它:
data\u transformer=transforms.Compose([
transforms.Resize((10,10)),
transforms.Grayscale(),
transforms.ToTensor(),
阈值变换(thr_255=240)
])
p data_transformer = transforms.Compose([
transforms.Resize((10, 10)),
transforms.Grayscale()
//transforms.ToTensor()
])
train_set = MyNewDataset(data_path, data_transformer, rows_train)