我正在尝试构建一个基于补丁的图像分类器网络,因此我想从.tif图像中提取补丁,然后将其保存为文件:
import cv2
import tensorflow as tf
import numpy as np
from PIL import Image
file = 'data/test/Benign/b001.tif'
patch_path = 'data/patches/'
k = 1495
s = 99
def extract_patches(img_file, img_name):
img = cv2.imread(img_file)
padd = tf.constant([[29, 29, ], [21, 20], [0, 0]])
img = tf.pad(img, padd, "CONSTANT")
img = tf.expand_dims(img, 0)
c = img.get_shape()[-1]
extracted = tf.extract_image_patches(
images=img,
ksizes=[1, k, k, 1],
strides=[1, s, s, 1],
rates=[1, 1, 1, 1],
padding='VALID')
patches_shape = extracted.shape
patches = tf.reshape(extracted, [tf.reduce_prod(patches_shape[0:3]), k, k, int(c)])
patch_num = patches.shape[0]
for i in range(patch_num):
sess = tf.Session()
curr_patch = patches[i]
print(type(curr_patch))
print(curr_patch.shape)
resized_patch = tf.image.resize_images(curr_patch, [299, 299], method=tf.image.ResizeMethod.BILINEAR)
print(type(resized_patch))
print(resized_patch.shape)
encode_patch = tf.image.encode_jpeg(resized_patch)
print(type(encode_patch))
print(encode_patch.shape)
fwrite = tf.write_file(patch_path + img_name + '/' + str(i) + '_' + img_name, encode_patch)
sess.run(fwrite)
extract_patches(file, 'test.tif')
这是我当前得到的输出:
类“tensorflow.python.framework.ops.tensor”
(1495, 1495, 3)
类“tensorflow.python.framework.ops.tensor”
(299, 299, 3)
回溯(最近一次呼叫的最后一次):
文件
“c:\users\mary\appdata\roaming\python\python36\site packages\tensorflow\python\framework\op_def_library.py”,
第510行,in _apply_op_helper preferred_dtype=default_dtype)
文件
“C:\users\mary\appdata\roaming\python\python36\site packages\tensorflow\python\framework\ops.py”,
第1104行,内部_将_转换为_张量
ret=转换函数(value,dtype=dtype,name=name,as_ref=as_ref)
文件
“C:\users\mary\appdata\roaming\python\python36\site packages\tensorflow\python\framework\ops.py”,
第947行,在TensortensorConversionFunction中
(dtype.name,t.dtype.name,str(t)))
值错误:张量转换请求的数据类型为uint8
D型
float32:'张量(“调整图像大小/挤压:0”,形状=(299、299、3),
dType=FLUAT32)
在处理上述异常期间,发生了另一个异常:
回溯(最近调用的最后一个):文件
“c:/users/mary/pycharmprojects/finetune_18_12_10/patchbazi.py”,第行
51,在
提取补丁(文件'test.tif')
文件“c:/users/mary/pycharmprojects/finetune_18_12_10/patchbazi.py”,
第43行,提取补片中
encode_patch=tf.image.encode_jpeg(调整大小的_patch)
文件
“C:\users\mary\appdata\roaming\python\python36\site packages\tensorflow\python\ops\gen_image_ops.py”,
第1439行,编码为\u jpeg
名称=名称)
文件
“c:\users\mary\appdata\roaming\python\python36\site packages\tensorflow\python\framework\op_def_library.py”,
第533行,输入应用帮助程序
(前缀,dtypes.as_dtype(input_arg.type).name)
类型错误:“encodejpeg”op的输入“image”的类型为float32
与预期的uint8类型不匹配。
进程已完成,退出代码为1
如你所见,当我试图
编码\u jpeg(调整大小的\u补丁)
,我得到类型不匹配错误。没有
tf.image.resize_images()。
,一切都很好地工作,所以我猜在调整大小函数中发生了一些类型更改。我也试着按照建议解码图像。
here
但显然解码器只适用于少数文件扩展名。有人能帮我吗?
我使用的是python 3.6.5和tensorflow 1.12.0