Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

It is recommended to use np.asarray instead of np.array to avoid unne… #1397

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/align/aligned_face.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ def original_roi(self) -> np.ndarray:
frame. """
with self._cache.lock("original_roi"):
if self._cache.original_roi is None:
roi = np.array([[0, 0],
roi = np.asarray([[0, 0],
[0, self._size - 1],
[self._size - 1, self._size - 1],
[self._size - 1, 0]])
Expand Down Expand Up @@ -650,7 +650,7 @@ def get_cropped_roi(self,
self.pose.offset[centering],
self._source_centering)
padding = target_size // 2
roi = np.array([center - padding, center + padding]).ravel()
roi = np.asarray([center - padding, center + padding]).ravel()
logger.trace( # type:ignore[attr-defined]
"centering: '%s', center: %s, padding: %s, sub roi: %s",
centering, center, padding, roi)
Expand Down
10 changes: 5 additions & 5 deletions lib/align/aligned_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def stored_mask(self) -> np.ndarray:
def original_roi(self) -> np.ndarray:
""" :class: `numpy.ndarray`: The original region of interest of the mask in the
source frame. """
points = np.array([[0, 0],
points = np.asarray([[0, 0],
[0, self.stored_size - 1],
[self.stored_size - 1, self.stored_size - 1],
[self.stored_size - 1, 0]], np.int32).reshape((-1, 1, 2))
Expand Down Expand Up @@ -287,7 +287,7 @@ def set_sub_crop(self,
centering,
self.stored_size,
coverage_ratio=coverage_ratio)
roi = np.array([center - crop_size // 2, center + crop_size // 2]).ravel()
roi = np.asarray([center - crop_size // 2, center + crop_size // 2]).ravel()

self._sub_crop_size = crop_size
self._sub_crop_slices["in"] = [slice(max(roi[1], 0), max(roi[3], 0)),
Expand Down Expand Up @@ -318,8 +318,8 @@ def _adjust_affine_matrix(self, mask_size: int, affine_matrix: np.ndarray) -> np
The affine matrix adjusted for the mask at its stored dimensions.
"""
zoom = self.stored_size / mask_size
zoom_mat = np.array([[zoom, 0, 0.], [0, zoom, 0.]])
adjust_mat = np.dot(zoom_mat, np.concatenate((affine_matrix, np.array([[0., 0., 1.]]))))
zoom_mat = np.asarray([[zoom, 0, 0.], [0, zoom, 0.]])
adjust_mat = np.dot(zoom_mat, np.concatenate((affine_matrix, np.asarray([[0., 0., 1.]]))))
logger.trace("storage_size: %s, mask_size: %s, zoom: %s, " # type:ignore[attr-defined]
"original matrix: %s, adjusted_matrix: %s", self.stored_size, mask_size, zoom,
affine_matrix.shape, adjust_mat.shape)
Expand Down Expand Up @@ -374,7 +374,7 @@ def from_dict(self, mask_dict: MaskAlignmentsFileDict) -> None:
self._mask = mask_dict["mask"]
affine_matrix = mask_dict["affine_matrix"]
self._affine_matrix = (affine_matrix if isinstance(affine_matrix, np.ndarray)
else np.array(affine_matrix, dtype="float64"))
else np.asarray(affine_matrix, dtype="float64"))
self._interpolator = mask_dict["interpolator"]
self.stored_size = mask_dict["stored_size"]
centering = mask_dict.get("stored_centering")
Expand Down
6 changes: 3 additions & 3 deletions lib/align/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ def from_shape(cls, shape: tuple[int, ...]) -> LandmarkType:


_MEAN_FACE: dict[LandmarkType, np.ndarray] = {
LandmarkType.LM_2D_4: np.array(
LandmarkType.LM_2D_4: np.asarray(
[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]), # Clockwise from TL
LandmarkType.LM_2D_51: np.array([
LandmarkType.LM_2D_51: np.asarray([
[0.010086, 0.106454], [0.085135, 0.038915], [0.191003, 0.018748], [0.300643, 0.034489],
[0.403270, 0.077391], [0.596729, 0.077391], [0.699356, 0.034489], [0.808997, 0.018748],
[0.914864, 0.038915], [0.989913, 0.106454], [0.500000, 0.203352], [0.500000, 0.307009],
Expand All @@ -66,7 +66,7 @@ def from_shape(cls, shape: tuple[int, ...]) -> LandmarkType:
[0.500000, 0.909281], [0.433405, 0.902192], [0.347967, 0.864805], [0.300252, 0.784792],
[0.437969, 0.778746], [0.500000, 0.785343], [0.562030, 0.778746], [0.699747, 0.784792],
[0.563237, 0.824182], [0.500000, 0.831803], [0.436763, 0.824182]]),
LandmarkType.LM_3D_26: np.array([
LandmarkType.LM_3D_26: np.asarray([
[4.056931, -11.432347, 1.636229], # 8 chin LL
[1.833492, -12.542305, 4.061275], # 7 chin L
[0.0, -12.901019, 4.070434], # 6 chin C
Expand Down
8 changes: 4 additions & 4 deletions lib/align/detected_face.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,8 +350,8 @@ def from_alignment(self, alignment: AlignmentFileDict,
self.height = alignment["h"]
landmarks = alignment["landmarks_xy"]
if not isinstance(landmarks, np.ndarray):
landmarks = np.array(landmarks, dtype="float32")
self._identity = {T.cast(T.Literal["vggface2"], k): np.array(v, dtype="float32")
landmarks = np.asarray(landmarks, dtype="float32")
self._identity = {T.cast(T.Literal["vggface2"], k): np.asarray(v, dtype="float32")
for k, v in alignment.get("identity", {}).items()}
self._landmarks_xy = landmarks.copy()

Expand Down Expand Up @@ -404,15 +404,15 @@ def from_png_meta(self, alignment: PNGHeaderAlignmentsDict) -> None:
self.width = alignment["w"]
self.top = alignment["y"]
self.height = alignment["h"]
self._landmarks_xy = np.array(alignment["landmarks_xy"], dtype="float32")
self._landmarks_xy = np.asarray(alignment["landmarks_xy"], dtype="float32")
self.mask = {}
for name, mask_dict in alignment["mask"].items():
self.mask[name] = Mask()
self.mask[name].from_dict(mask_dict)
self._identity = {}
for key, val in alignment.get("identity", {}).items():
assert key in ["vggface2"]
self._identity[T.cast(T.Literal["vggface2"], key)] = np.array(val, dtype="float32")
self._identity[T.cast(T.Literal["vggface2"], key)] = np.asarray(val, dtype="float32")
logger.trace("Created from png exif header: (left: %s, " # type:ignore[attr-defined]
"width: %s, top: %s height: %s, landmarks: %s, mask: %s, identity: %s)",
self.left, self.width, self.top, self.height, self.landmarks_xy, self.mask,
Expand Down
16 changes: 8 additions & 8 deletions lib/align/pose.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def xyz_2d(self) -> np.ndarray:
""" :class:`numpy.ndarray` projected (x, y) coordinates for each x, y, z point at a
constant distance from adjusted center of the skull (0.5, 0.5) in the 2D space. """
if self._xyz_2d is None:
xyz = cv2.projectPoints(np.array([[6., 0., -2.3],
xyz = cv2.projectPoints(np.asarray([[6., 0., -2.3],
[0., 6., -2.3],
[0., 0., 3.7]]).astype("float32"),
self._rotation,
Expand Down Expand Up @@ -119,7 +119,7 @@ def _get_camera_matrix(cls) -> np.ndarray:
An estimated camera matrix
"""
focal_length = 4
camera_matrix = np.array([[focal_length, 0, 0.5],
camera_matrix = np.asarray([[focal_length, 0, 0.5],
[0, focal_length, 0.5],
[0, 0, 1]], dtype="double")
logger.trace("camera_matrix: %s", camera_matrix) # type:ignore[attr-defined]
Expand All @@ -145,7 +145,7 @@ def _solve_pnp(self, landmarks: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""
if self._landmarks_type != LandmarkType.LM_2D_68:
points: np.ndarray = np.empty([])
rotation = np.array([[0.0], [0.0], [0.0]])
rotation = np.asarray([[0.0], [0.0], [0.0]])
translation = rotation.copy()
else:
points = landmarks[[6, 7, 8, 9, 10, 17, 21, 22, 26, 31, 32, 33, 34,
Expand All @@ -168,20 +168,20 @@ def _get_offset(self) -> dict[CenteringType, np.ndarray]:
:class:`numpy.ndarray`
The x, y offset of the new center from the old center.
"""
offset: dict[CenteringType, np.ndarray] = {"legacy": np.array([0.0, 0.0])}
offset: dict[CenteringType, np.ndarray] = {"legacy": np.asarray([0.0, 0.0])}
if self._landmarks_type != LandmarkType.LM_2D_68:
offset["face"] = np.array([0.0, 0.0])
offset["head"] = np.array([0.0, 0.0])
offset["face"] = np.asarray([0.0, 0.0])
offset["head"] = np.asarray([0.0, 0.0])
else:
points: dict[T.Literal["face", "head"], tuple[float, ...]] = {"head": (0.0, 0.0, -2.3),
"face": (0.0, -1.5, 4.2)}
for key, pnts in points.items():
center = cv2.projectPoints(np.array([pnts]).astype("float32"),
center = cv2.projectPoints(np.asarray([pnts]).astype("float32"),
self._rotation,
self._translation,
self._camera_matrix,
self._distortion_coefficients)[0].squeeze()
logger.trace("center %s: %s", key, center) # type:ignore[attr-defined]
offset[key] = center - np.array([0.5, 0.5])
offset[key] = center - np.asarray([0.5, 0.5])
logger.trace("offset: %s", offset) # type:ignore[attr-defined]
return offset
2 changes: 1 addition & 1 deletion lib/align/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def update(self) -> int:
for alignment in val["faces"]:
test = alignment["landmarks_xy"]
if not isinstance(test, np.ndarray):
alignment["landmarks_xy"] = np.array(test, dtype="float32")
alignment["landmarks_xy"] = np.asarray(test, dtype="float32")
update_count += 1
return update_count

Expand Down
8 changes: 4 additions & 4 deletions lib/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def _get_warp_matrix(self, matrix: np.ndarray, size: int) -> np.ndarray:
else:
mat = matrix * self._face_scale
patch_center = (size / 2, size / 2)
mat[..., 2] += (1 - self._face_scale) * np.array(patch_center)
mat[..., 2] += (1 - self._face_scale) * np.asarray(patch_center)

return mat

Expand Down Expand Up @@ -282,7 +282,7 @@ def _patch_image(self, predicted: ConvertItem) -> np.ndarray | list[bytes]:
kwargs: dict[str, T.Any] = {}
if self.cli_arguments.writer == "patch":
kwargs["canvas_size"] = (background.shape[1], background.shape[0])
kwargs["matrices"] = np.array([self._get_warp_matrix(face.adjusted_matrix,
kwargs["matrices"] = np.asarray([self._get_warp_matrix(face.adjusted_matrix,
patched_face.shape[1])
for face in predicted.reference_faces],
dtype="float32")
Expand Down Expand Up @@ -349,7 +349,7 @@ def _get_new_image(self,

placeholder = np.zeros((frame_size[1], frame_size[0], 4), dtype="float32")
if self._full_frame_output:
background = predicted.inbound.image / np.array(255.0, dtype="float32")
background = predicted.inbound.image / np.asarray(255.0, dtype="float32")
placeholder[:, :, :3] = background
else:
faces = [] # Collect the faces into final array
Expand All @@ -373,7 +373,7 @@ def _get_new_image(self,
faces.append(new_face)

if not self._full_frame_output:
placeholder = np.array(faces, dtype="float32")
placeholder = np.asarray(faces, dtype="float32")

logger.trace("Got filename: '%s'. (placeholders: %s)", # type: ignore[attr-defined]
predicted.inbound.filename, placeholder.shape)
Expand Down
4 changes: 2 additions & 2 deletions lib/gui/analysis/event_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def _to_numpy(self,
del loss[idx]
del times[idx]

n_times, n_loss = (np.array(times, dtype="float64"), np.array(loss, dtype="float32"))
n_times, n_loss = (np.asarray(times, dtype="float64"), np.asarray(loss, dtype="float32"))
logger.debug("Converted to numpy: (data points: %s, timestamps shape: %s, loss shape: %s)",
len(data), n_times.shape, n_loss.shape)

Expand Down Expand Up @@ -756,7 +756,7 @@ def _get_outputs(cls, model_config: dict[str, T.Any]) -> np.ndarray:
:class:`numpy.ndarray`
The layer output names, their instance index and their output index
"""
outputs = np.array(model_config["output_layers"])
outputs = np.asarray(model_config["output_layers"])
logger.debug("Obtained model outputs: %s, shape: %s", outputs, outputs.shape)
if outputs.ndim == 2: # Insert extra dimension for non learn mask models
outputs = np.expand_dims(outputs, axis=1)
Expand Down
10 changes: 5 additions & 5 deletions lib/gui/analysis/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def get_loss(self, session_id: int | None) -> dict[str, np.ndarray]:
for key in sorted(loss_dict):
for loss_key, loss in loss_dict[key].items():
all_loss.setdefault(loss_key, []).extend(loss)
retval: dict[str, np.ndarray] = {key: np.array(val, dtype="float32")
retval: dict[str, np.ndarray] = {key: np.asarray(val, dtype="float32")
for key, val in all_loss.items()}
else:
retval = loss_dict.get(session_id, {})
Expand Down Expand Up @@ -671,7 +671,7 @@ def _get_raw(self) -> None:
if len(iterations) > 1:
# Crop all losses to the same number of items
if self._iterations == 0:
self._stats = {lossname: np.array([], dtype=loss.dtype)
self._stats = {lossname: np.asarray([], dtype=loss.dtype)
for lossname, loss in self.stats.items()}
else:
self._stats = {lossname: loss[:self._iterations]
Expand Down Expand Up @@ -760,7 +760,7 @@ def _calc_rate_total(cls) -> np.ndarray:
batchsize = batchsizes[sess_id]
timestamps = total_timestamps[sess_id]
rate.extend((batchsize * 2) / np.diff(timestamps))
retval = np.array(rate)
retval = np.asarray(rate)
logger.debug("Calculated totals rate: Item_count: %s", len(retval))
return retval

Expand Down Expand Up @@ -801,7 +801,7 @@ def _calc_avg(self, data: np.ndarray) -> np.ndarray:

if datapoints <= (self._args["avg_samples"] * 2):
logger.info("Not enough data to compile rolling average")
return np.array([], dtype="float64")
return np.asarray([], dtype="float64")

avgs = np.cumsum(np.nan_to_num(data), dtype="float64")
avgs[window:] = avgs[window:] - avgs[:-window]
Expand Down Expand Up @@ -984,7 +984,7 @@ def _ewma_vectorized(self,
out /= scaling_factors[-2::-1] # cumulative sums / scaling

if offset != 0:
noffset = np.array(offset, copy=False).astype(self._dtype, copy=False)
noffset = np.asarray(offset, copy=False).astype(self._dtype, copy=False)
out += noffset * scaling_factors[1:]

def _ewma_vectorized_2d(self, data: np.ndarray, out: np.ndarray) -> None:
Expand Down
4 changes: 2 additions & 2 deletions lib/gui/custom_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,10 +841,10 @@ def __init__(self, title, total):
self._lbl_title = self._set_title(title)
self._progress_bar = self._get_progress_bar()

offset = np.array((self.master.winfo_rootx(), self.master.winfo_rooty()))
offset = np.asarray((self.master.winfo_rootx(), self.master.winfo_rooty()))
# TODO find way to get dimensions of the pop up without it flicking onto the screen
self.update_idletasks()
center = np.array((
center = np.asarray((
(self.master.winfo_width() // 2) - (self.winfo_width() // 2),
(self.master.winfo_height() // 2) - (self.winfo_height() // 2))) + offset
self.wm_geometry(f"+{center[0]}+{center[1]}")
Expand Down
6 changes: 3 additions & 3 deletions lib/gui/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def _pad_and_border(self, image: Image.Image, size: int) -> np.ndarray:
image = new_img
draw = ImageDraw.Draw(image)
draw.rectangle(((0, 0), (size, size)), outline="#E5E5E5", width=1)
retval = np.array(image)
retval = np.asarray(image)
logger.trace("image shape: %s", retval.shape) # type: ignore
return retval

Expand All @@ -296,7 +296,7 @@ def _process_samples(self,
bool
``True`` if samples succesfully compiled otherwise ``False``
"""
asamples = np.array(samples)
asamples = np.asarray(samples)
if not np.any(asamples):
logger.debug("No preview images collected.")
return False
Expand Down Expand Up @@ -397,7 +397,7 @@ def _create_placeholder(self, thumbnail_size: int) -> None:
placeholder = Image.new("RGB", (thumbnail_size, thumbnail_size))
draw = ImageDraw.Draw(placeholder)
draw.rectangle(((0, 0), (thumbnail_size, thumbnail_size)), outline="#E5E5E5", width=1)
placeholder = np.array(placeholder)
placeholder = np.asarray(placeholder)
self._placeholder = placeholder
logger.debug("Created placeholder. shape: %s", placeholder.shape)

Expand Down
2 changes: 1 addition & 1 deletion lib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ def read_image_batch(filenames, with_metadata=False):
else:
batch[ret_idx] = future.result()

batch = np.array(batch)
batch = np.asarray(batch)
retval = (batch, meta) if with_metadata else batch
logger.trace("Returning images: (filenames: %s, batch shape: %s, with_metadata: %s)",
filenames, batch.shape, with_metadata)
Expand Down
4 changes: 2 additions & 2 deletions lib/keras_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def __init__(self, from_space: str, to_space: str) -> None:
raise ValueError(f"The color transform {from_space} to {to_space} is not defined.")

self._func = functions[func_name]
self._ref_illuminant = K.constant(np.array([[[0.950428545, 1.000000000, 1.088900371]]]),
self._ref_illuminant = K.constant(np.asarray([[[0.950428545, 1.000000000, 1.088900371]]]),
dtype="float32")
self._inv_ref_illuminant = 1. / self._ref_illuminant

Expand All @@ -125,7 +125,7 @@ def _get_rgb_xyz_map(cls) -> tuple[Tensor, Tensor]:
tuple
The mapping and inverse Tensors for rgb to xyz color space conversion
"""
mapping = np.array([[10135552 / 24577794, 8788810 / 24577794, 4435075 / 24577794],
mapping = np.asarray([[10135552 / 24577794, 8788810 / 24577794, 4435075 / 24577794],
[2613072 / 12288897, 8788810 / 12288897, 887015 / 12288897],
[1425312 / 73733382, 8788810 / 73733382, 70074185 / 73733382]])
inverse = np.linalg.inv(mapping)
Expand Down
2 changes: 1 addition & 1 deletion lib/model/autoclip.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _percentile(self, grad_history: tf.Tensor) -> tf.Tensor:
constant_values=1)
nan_batch_members = tf.reshape(nan_batch_members, shape=right_rank_matched_shape)

nan = np.array(np.nan, gathered_hist.dtype.as_numpy_dtype)
nan = np.asarray(np.nan, gathered_hist.dtype.as_numpy_dtype)
gathered_hist = tf.where(nan_batch_members, nan, gathered_hist)

return gathered_hist
Expand Down
2 changes: 1 addition & 1 deletion lib/model/initializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def _symmetrize(var_a):
""" Make the given tensor symmetrical. """
var_b = np.transpose(var_a, axes=(0, 1, 3, 2))
diag = var_a.diagonal(axis1=2, axis2=3)
var_c = np.array([[np.diag(arr) for arr in batch] for batch in diag])
var_c = np.asarray([[np.diag(arr) for arr in batch] for batch in diag])
return var_a + var_b - var_c

@staticmethod
Expand Down
Loading