MCPcopy Create free account
hub / github.com/IceClear/StableSR / img2tensor

Function img2tensor

scripts/util_image.py:275–309  ·  view source on GitHub ↗

Convert image numpy arrays into torch tensor. Args: imgs (Array or list[array]): Accept shapes: 3) list of numpy arrays 1) 3D numpy array of shape (H x W x 3/1); 2) 2D Tensor of shape (H x W). Tensor channel should be in RGB order. Ret

(imgs, out_type=torch.float32)

Source from the content-addressed store, hash-verified

273 return result
274
275def img2tensor(imgs, out_type=torch.float32):
276 """Convert image numpy arrays into torch tensor.
277 Args:
278 imgs (Array or list[array]): Accept shapes:
279 3) list of numpy arrays
280 1) 3D numpy array of shape (H x W x 3/1);
281 2) 2D Tensor of shape (H x W).
282 Tensor channel should be in RGB order.
283
284 Returns:
285 (array or list): 4D ndarray of shape (1 x C x H x W)
286 """
287
288 def _img2tensor(img):
289 if img.ndim == 2:
290 tensor = torch.from_numpy(img[None, None,]).type(out_type)
291 elif img.ndim == 3:
292 tensor = torch.from_numpy(rearrange(img, 'h w c -> c h w')).type(out_type).unsqueeze(0)
293 else:
294 raise TypeError(f'2D or 3D numpy array expected, got{img.ndim}D array')
295 return tensor
296
297 if not (isinstance(imgs, np.ndarray) or (isinstance(imgs, list) and all(isinstance(t, np.ndarray) for t in imgs))):
298 raise TypeError(f'Numpy array or list of numpy array expected, got {type(imgs)}')
299
300 flag_numpy = isinstance(imgs, np.ndarray)
301 if flag_numpy:
302 imgs = [imgs,]
303 result = []
304 for _img in imgs:
305 result.append(_img2tensor(_img))
306
307 if len(result) == 1 and flag_numpy:
308 result = result[0]
309 return result
310
311# ------------------------Image I/O-----------------------------
312def imread(path, chn='rgb', dtype='float32'):

Callers

nothing calls this directly

Calls 1

_img2tensorFunction · 0.85

Tested by

no test coverage detected