python 代码如下
def get_enchance(image):
print(image.shape)
model = GetModel(opt)
parameters_name = 'C:/liaomingwei/Seg_prediction/checkpoints/007_LinHuiMin_FocalWDice2000_2_epoch_3.ckpt'
model_CKPT = torch.load(parameters_name)
model.load_state_dict(model_CKPT['state_dict'])
tifffile.imsave('E:\\test.tif', image)
print('loading checkpoint!')
patch_size = np.array([120, 120, 120])
overlap = np.array([10, 10, 10])
patch_indices = compute_patch_indices(image.shape, patch_size, overlap, start=0)
#return image
Tdataset = GenerateDataset_ForNew(image, image.shape, patch_size, overlap)
val_loader = DataLoader(Tdataset, batch_size=3, num_workers=2, shuffle=False)
prob_patches = test_model(val_loader, model)
print('run here2')
start = time.time()
patchindices = compute_patch_indices(image.shape, patch_size, overlap, start=0)
prob_recon = reconstruct_from_patches(prob_patches, patch_indices, image.shape)
print('run here3!')
prob_recon = prob_recon * 255
prob_recon = prob_recon.astype(np.uint8)
run_time = time.time() - start
print(run_time)
print('ok')
return prob_recon
def test_model(val_loader,model):
model.eval()
pred_Patches = []
prob_patches =[]
# image_Patches = []
soft_max = nn.Softmax(dim=1)
start_time=time.time()
print('run here')
try:
for batch_ids, (image_patch) in enumerate(val_loader):
print('*'*100)
print('run here1')
print(batch_ids)
if opt.use_cuda:
image_patch=image_patch.cuda()
output=model(image_patch)
with torch.no_grad():
# just 0 and 1
_,pred_patch = torch.max(output,dim=1)
# for prob
prob_patch = soft_max(output)
del output
pred_patch=pred_patch.cpu().numpy()
prob_patch = prob_patch.cpu().numpy()
prob_patch = prob_patch[:, 1, ...]
# image_patch=image_patch.cpu().numpy()
for image_num in range(pred_patch.shape[0]):
# 0 and 1
pred1=np.array(pred_patch[image_num, :, :, :], dtype=np.float32)
pred_Patches.append( pred1 )
# prob
prob1 = np.array(prob_patch[image_num, :, :, :], dtype=np.float32)
prob_patches.append(prob1)
#tifffile.imsave(os.path.join('D:\Data\Osten\\6\Osten' + '\prob', str(batch_ids)+'_'+str(image_num) + '_probtest.tif'), np.uint8(prob1*255))
# image1=np.array(image_patch[image_num,0,:,:,:], dtype=np.float32)
# image_Patches.append(image1)
except Exception as e:
print('except:', e)
# save the images into npy type
run_time=time.time()-start_time
print(run_time)
return prob_patches
c++代码如下
Image *Im = new Image();//定义的一个读写图片的类,用的tif库
std::string path = "E:/testimage/0.tif";
std::string outpath = "E:/testimage/0.1.tif";
int width;
int height;//获取图片的高
TIFF *tif = TIFFOpen(path.c_str(), "r"); //使用TIFFOpen函数以只读形式打开图像。
int depth = TIFFNumberOfDirectories(tif);
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
TIFFClose(tif);
uint16 *nImage = new uint16[width*height*depth];
uint8 *outimage = new uint8[width*height*depth];
memset(outimage, 0, width*height*depth);
memset(nImage, 0, sizeof(uint16)*width*height*depth);
//clock_t start, end;
//start = clock();
Im->read_3d_buffer(path.c_str(), nImage, width, height, depth);
//Py_SetProgramName(L"C:/Program Files/Python36");
//Py_SetPythonHome(L"C:/Program Files/Python36");
Py_Initialize();
import_array();
//Run a simple string
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('C:/liaomingwei/Seg_prediction')");
PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
pName = PyUnicode_FromString((char*)"Predict_10Data");
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule, (char*)"get_enchance");
npy_intp Dims[3] = { width, height, depth };
PyObject*PyArray = PyArray_SimpleNewFromData(3, Dims, NPY_USHORT, nImage);
PyObject*ArgArray = PyTuple_New(1);
PyTuple_SetItem(ArgArray, 0, PyArray);
pValue = PyObject_CallObject(pFunc, ArgArray);
auto result = _PyUnicode_AsString(pValue);
std::cout << result << std::endl;
Py_Finalize();
运行结果如下
一直在重复运行,有大佬帮忙看看啥问题吗