MCPcopy Create free account
hub / github.com/aigc3d/LHM / read_image

Method read_image

engine/SegmentAPI/base.py:188–240  ·  view source on GitHub ↗

read an image file into various formats and color mode. Args: path (str): path to the image file. mode (Literal["float", "uint8", "pil", "torch", "tensor"], optional): returned image format. Defaults to "float". float: float32 numpy array, range [0, 1

(
        self,
        path,
        mode,
        order,
    )

Source from the content-addressed store, hash-verified

186 return torch.from_numpy(data)
187
188 def read_image(
189 self,
190 path,
191 mode,
192 order,
193 ):
194 """read an image file into various formats and color mode.
195
196 Args:
197 path (str): path to the image file.
198 mode (Literal["float", "uint8", "pil", "torch", "tensor"], optional): returned image format. Defaults to "float".
199 float: float32 numpy array, range [0, 1];
200 uint8: uint8 numpy array, range [0, 255];
201 pil: PIL image;
202 torch/tensor: float32 torch tensor, range [0, 1];
203 order (Literal["RGB", "RGBA", "BGR", "BGRA"], optional): channel order. Defaults to "RGB".
204
205 Note:
206 By default this function will convert RGBA image to white-background RGB image. Use ``order="RGBA"`` to keep the alpha channel.
207
208 Returns:
209 Union[np.ndarray, PIL.Image, torch.Tensor]: the image array.
210 """
211
212 if mode == "pil":
213 return Image.open(path).convert(order)
214
215 img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
216
217 # cvtColor
218 if len(img.shape) == 3: # ignore if gray scale
219 if order in ["RGB", "RGBA"]:
220 if img.shape[-1] == 4:
221 img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)
222 elif img.shape[-1] == 3:
223 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
224
225 # mix background
226 if img.shape[-1] == 4 and "A" not in order:
227 img = img.astype(np.float32) / 255
228 img = img[..., :3] * img[..., 3:] + (1 - img[..., 3:])
229
230 # mode
231 if mode == "uint8":
232 if img.dtype != np.uint8:
233 img = (img * 255).astype(np.uint8)
234 elif mode == "float":
235 if img.dtype == np.uint8:
236 img = img.astype(np.float32) / 255
237 else:
238 raise ValueError(f"Unknown read_image mode {mode}")
239
240 return img

Callers 1

__init__Method · 0.95

Calls 1

convertMethod · 0.80

Tested by

no test coverage detected