pixelflow 0.8.0__tar.gz → 0.10.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. {pixelflow-0.8.0/pixelflow.egg-info → pixelflow-0.10.0}/PKG-INFO +1 -1
  2. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/__init__.py +1 -1
  3. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/media.py +188 -61
  4. {pixelflow-0.8.0 → pixelflow-0.10.0/pixelflow.egg-info}/PKG-INFO +1 -1
  5. {pixelflow-0.8.0 → pixelflow-0.10.0}/LICENSE +0 -0
  6. {pixelflow-0.8.0 → pixelflow-0.10.0}/NOTICE +0 -0
  7. {pixelflow-0.8.0 → pixelflow-0.10.0}/README.md +0 -0
  8. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/__init__.py +0 -0
  9. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/anchors.py +0 -0
  10. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/blur.py +0 -0
  11. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/box.py +0 -0
  12. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/classification.py +0 -0
  13. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/crossing.py +0 -0
  14. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/dot.py +0 -0
  15. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/filled_box.py +0 -0
  16. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/fps_counter.py +0 -0
  17. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/grid_overlay.py +0 -0
  18. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/heatmap.py +0 -0
  19. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/keypoint.py +0 -0
  20. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/keypoint_skeleton.py +0 -0
  21. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/label.py +0 -0
  22. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/mask.py +0 -0
  23. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/motion_dots.py +0 -0
  24. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/motion_trails.py +0 -0
  25. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/oval.py +0 -0
  26. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/pixelate.py +0 -0
  27. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/polygon.py +0 -0
  28. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/scale_bar.py +0 -0
  29. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/utils.py +0 -0
  30. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/annotators/zones.py +0 -0
  31. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/arrays.py +0 -0
  32. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/buffer.py +0 -0
  33. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/classifications/__init__.py +0 -0
  34. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/classifications/classifications.py +0 -0
  35. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/classifications/converters.py +0 -0
  36. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/colors.py +0 -0
  37. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/crossings.py +0 -0
  38. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/detections/__init__.py +0 -0
  39. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/detections/converters.py +0 -0
  40. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/detections/detections.py +0 -0
  41. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/detections/filters.py +0 -0
  42. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/labels.py +0 -0
  43. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/masks.py +0 -0
  44. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/serialization.py +0 -0
  45. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/slicer.py +0 -0
  46. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/smoother.py +0 -0
  47. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/strategies.py +0 -0
  48. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/timer.py +0 -0
  49. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/UPSTREAM.md +0 -0
  50. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/__init__.py +0 -0
  51. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/base.py +0 -0
  52. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/botsort/__init__.py +0 -0
  53. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/botsort/tracker.py +0 -0
  54. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/botsort/tracklet.py +0 -0
  55. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/botsort/utils.py +0 -0
  56. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/bytetrack/__init__.py +0 -0
  57. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/bytetrack/tracker.py +0 -0
  58. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/bytetrack/tracklet.py +0 -0
  59. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/bytetrack/utils.py +0 -0
  60. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/cbiou/__init__.py +0 -0
  61. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/cbiou/tracker.py +0 -0
  62. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/ocsort/__init__.py +0 -0
  63. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/ocsort/tracker.py +0 -0
  64. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/ocsort/tracklet.py +0 -0
  65. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/ocsort/utils.py +0 -0
  66. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/sort/__init__.py +0 -0
  67. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/sort/tracker.py +0 -0
  68. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/sort/tracklet.py +0 -0
  69. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/sort/utils.py +0 -0
  70. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/__init__.py +0 -0
  71. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/base_tracklet.py +0 -0
  72. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/cmc.py +0 -0
  73. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/converters.py +0 -0
  74. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/iou.py +0 -0
  75. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/kalman_filter.py +0 -0
  76. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/matrix.py +0 -0
  77. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/motion_models.py +0 -0
  78. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/predict_timing.py +0 -0
  79. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/scale_aware_tracklet.py +0 -0
  80. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/tracker/utils/state_representations.py +0 -0
  81. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/transforms/__init__.py +0 -0
  82. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/transforms/detections.py +0 -0
  83. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/transforms/image.py +0 -0
  84. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/transforms/inverse.py +0 -0
  85. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/validators.py +0 -0
  86. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow/zones.py +0 -0
  87. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow.egg-info/SOURCES.txt +0 -0
  88. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow.egg-info/dependency_links.txt +0 -0
  89. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow.egg-info/requires.txt +0 -0
  90. {pixelflow-0.8.0 → pixelflow-0.10.0}/pixelflow.egg-info/top_level.txt +0 -0
  91. {pixelflow-0.8.0 → pixelflow-0.10.0}/pyproject.toml +0 -0
  92. {pixelflow-0.8.0 → pixelflow-0.10.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pixelflow
3
- Version: 0.8.0
3
+ Version: 0.10.0
4
4
  Summary: Computer vision processing library for visualizing and analyzing detection results from ML models
5
5
  Author-email: Emrah Nazif <emrah@datamarkin.com>
6
6
  License: Apache-2.0
@@ -1,4 +1,4 @@
1
- __version__ = "0.8.0"
1
+ __version__ = "0.10.0"
2
2
  __author__ = "Emrah NAZIF"
3
3
 
4
4
  # Import core modules
@@ -143,8 +143,12 @@ def _resolve_path(source: str) -> Path:
143
143
  # read_image is skipped for it -- which is most of any real dataset.
144
144
  _ALPHA_CAPABLE = frozenset({".png", ".gif", ".webp", ".tif", ".tiff", ".jp2"})
145
145
 
146
+ # Formats that keep an RGBA image's alpha when written. OpenCV writes a 4-channel array
147
+ # to JPEG or BMP too, dropping the alpha without a word, so RGBA goes only to these.
148
+ _ALPHA_WRITABLE = frozenset({".png", ".webp", ".tif", ".tiff"})
146
149
 
147
- def _require_rgb(image, what: str = "frame") -> None:
150
+
151
+ def _require_rgb(image, what: str = "frame", alpha: bool = False) -> None:
148
152
  """Raise unless ``image`` is the RGB uint8 HxWx3 array this library passes around.
149
153
 
150
154
  ``cv2.cvtColor`` accepts a 2D or 4-channel array for ``RGB2BGR`` and quietly
@@ -156,15 +160,19 @@ def _require_rgb(image, what: str = "frame") -> None:
156
160
  BGR are the same bytes in a different sequence, and no inspection recovers which
157
161
  one you have. So every array entering this library is **taken** to be RGB, at
158
162
  every boundary, not just this one.
163
+
164
+ ``alpha=True`` also accepts RGBA uint8 HxWx4, for the encoders, which convert it
165
+ themselves (see ``_to_bgr``). Every other boundary takes RGB only.
159
166
  """
167
+ if alpha:
168
+ expected, channels = "an RGB uint8 HxWx3 or RGBA HxWx4", (3, 4)
169
+ else:
170
+ expected, channels = "an RGB uint8 HxWx3", (3,)
160
171
  if not isinstance(image, np.ndarray):
172
+ raise ValueError(f"expected {expected} {what}, got {type(image).__name__}")
173
+ if image.ndim != 3 or image.shape[2] not in channels or image.dtype != np.uint8:
161
174
  raise ValueError(
162
- f"expected an RGB uint8 HxWx3 {what}, got {type(image).__name__}"
163
- )
164
- if image.ndim != 3 or image.shape[2] != 3 or image.dtype != np.uint8:
165
- raise ValueError(
166
- f"expected an RGB uint8 HxWx3 {what}, got shape {image.shape} "
167
- f"dtype {image.dtype}"
175
+ f"expected {expected} {what}, got shape {image.shape} dtype {image.dtype}"
168
176
  )
169
177
 
170
178
 
@@ -329,11 +337,19 @@ class _FrameSource:
329
337
  if self._pending is not None:
330
338
  frame, self._pending = self._pending, None
331
339
  return frame
332
- if self._cap is None or not self._cap.grab():
340
+ if self._cap is None or not self._grab():
333
341
  return None
334
342
  frame = self._retrieve_rgb()
335
343
  return None if frame is None else self._hand_out(frame)
336
344
 
345
+ def _grab(self) -> bool:
346
+ """Decode the next frame without converting it. False when the source ends."""
347
+ return self._cap.grab()
348
+
349
+ def _keeper(self):
350
+ """A test, called after each grab with its index, of whether to yield that frame."""
351
+ return lambda index: index % self._stride == 0
352
+
337
353
  def __iter__(self) -> Iterator[np.ndarray]:
338
354
  """Yield RGB frames from the current position until the source ends.
339
355
 
@@ -346,6 +362,7 @@ class _FrameSource:
346
362
  so they must be walked; they need not be turned into arrays.
347
363
  """
348
364
  index = 0
365
+ keep = self._keeper()
349
366
 
350
367
  # A source that decoded a frame in order to learn its own size hands that
351
368
  # frame out here rather than discarding it. Dropping it would silently skip
@@ -356,9 +373,9 @@ class _FrameSource:
356
373
  index = 1
357
374
 
358
375
  while self._cap is not None:
359
- if not self._cap.grab():
376
+ if not self._grab():
360
377
  break
361
- if index % self._stride == 0:
378
+ if keep(index):
362
379
  frame = self._retrieve_rgb()
363
380
  if frame is None:
364
381
  break
@@ -412,6 +429,12 @@ class VideoReader(_FrameSource):
412
429
  stride: Yield every Nth frame. ``fps`` and ``frames`` are divided to match,
413
430
  so a writer built with ``like=`` stays correct.
414
431
  start: Frame to begin at. Equivalent to ``seek(start)`` after opening.
432
+ rate: Yield this many frames a second instead of every Nth: the first frame of
433
+ every ``1/rate`` seconds, by the frames' own times, so a video whose frame rate
434
+ changes as it plays is sampled evenly too. ``fps`` is the rate. Not with
435
+ ``stride``.
436
+
437
+ After a frame is returned, ``frame_number`` and ``frame_time`` say which frame it is.
415
438
 
416
439
  Example:
417
440
  >>> video = pf.VideoReader("input.mp4", stride=2)
@@ -425,10 +448,15 @@ class VideoReader(_FrameSource):
425
448
  """
426
449
 
427
450
  def __init__(self, source: str, *, stride: int = 1, start: int = 0,
428
- width=_UNSET):
451
+ rate: Optional[float] = None, width=_UNSET):
429
452
  _reject_width(width, "VideoReader")
430
453
  if stride < 1:
431
454
  raise ValueError(f"stride must be at least 1, got {stride}")
455
+ self._rate = None if rate is None else _valid_fps(rate)
456
+ if rate is not None and self._rate is None:
457
+ raise ValueError(f"rate must be a positive number of frames a second, got {rate!r}")
458
+ if rate is not None and stride != 1:
459
+ raise ValueError("give stride or rate, not both: each says which frames to read")
432
460
 
433
461
  path = _resolve_path(source)
434
462
  self._source = str(path)
@@ -452,10 +480,53 @@ class VideoReader(_FrameSource):
452
480
 
453
481
  # Frame times learned by read_frame, in ms; they grow only as far as it is asked.
454
482
  self._times: list[float] = []
483
+ # The number of the next frame a grab decodes, and the time of the last one: see _grab.
484
+ self._next = 0
485
+ self._grabbed_time: Optional[float] = None
486
+ self._frame_number: Optional[int] = None
487
+ self._frame_time: Optional[float] = None
455
488
 
456
489
  if start:
457
490
  self.seek(start)
458
491
 
492
+ @property
493
+ def fps(self) -> Optional[float]:
494
+ """Rate of the frames this reader yields, or None if unknown.
495
+
496
+ Divided by ``stride``. With ``rate``, the rate, capped at the source's own: an
497
+ upper bound for a video with parts slower than the rate, which yield every frame.
498
+ """
499
+ if self._rate is None:
500
+ return super().fps
501
+ return self._rate if self._source_fps is None else min(self._rate, self._source_fps)
502
+
503
+ @property
504
+ def frames(self) -> Optional[int]:
505
+ """Estimated number of frames this reader will yield, or None if unknown."""
506
+ if self._rate is None or self.duration is None:
507
+ return super().frames
508
+ return min(self._source_frames, math.ceil(self.duration * self._rate))
509
+
510
+ @property
511
+ def frame_number(self) -> Optional[int]:
512
+ """Number in the file, from 0, of the frame last returned; None before the first.
513
+
514
+ Counts every frame of the file, whatever ``stride`` or ``rate`` is, so a result
515
+ can be drawn back on the original frame or read again with :meth:`read_frame`.
516
+ After :meth:`seek` in a video whose frame rate changes, it is only as exact as the
517
+ seek; :meth:`read_frame` is always exact.
518
+ """
519
+ return self._frame_number
520
+
521
+ @property
522
+ def frame_time(self) -> Optional[float]:
523
+ """Time in the file, in milliseconds, of the frame last returned; None before the first.
524
+
525
+ The frame's own time, so it stays right when the frame rate changes. A tracker
526
+ takes it as ``timestamp`` (in seconds: ``frame_time / 1000``).
527
+ """
528
+ return self._frame_time
529
+
459
530
  @property
460
531
  def codec(self) -> str:
461
532
  """FourCC of the source stream.
@@ -473,6 +544,39 @@ class VideoReader(_FrameSource):
473
544
  video (common in phone recordings). :meth:`read_frame` is exact.
474
545
  """
475
546
  self._cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
547
+ self._next = frame_number
548
+
549
+ def _grab(self) -> bool:
550
+ """Decode the next frame, keeping its number and its time."""
551
+ if not self._cap.grab():
552
+ return False
553
+ self._next += 1
554
+ self._grabbed_time = self._cap.get(cv2.CAP_PROP_POS_MSEC)
555
+ return True
556
+
557
+ def _hand_out(self, frame: np.ndarray) -> np.ndarray:
558
+ self._frame_number, self._frame_time = self._next - 1, self._grabbed_time
559
+ return super()._hand_out(frame)
560
+
561
+ def _keeper(self):
562
+ """With ``rate``: keep the first frame of each 1/rate seconds, by the frames' times."""
563
+ if self._rate is None:
564
+ return super()._keeper()
565
+ first, last = None, -1
566
+
567
+ def keep(index: int) -> bool:
568
+ nonlocal first, last
569
+ time = self._grabbed_time
570
+ if first is None:
571
+ first = time
572
+ # The slack keeps a frame exactly on a boundary in the stretch it starts.
573
+ stretch = int((time - first + _FRAME_TIME_SLACK_MS) * self._rate / 1000)
574
+ if stretch <= last:
575
+ return False
576
+ last = stretch
577
+ return True
578
+
579
+ return keep
476
580
 
477
581
  def timestamps(self) -> list[float]:
478
582
  """Every frame's time in the file, in milliseconds, in order.
@@ -504,21 +608,20 @@ class VideoReader(_FrameSource):
504
608
  if number < 0:
505
609
  raise IndexError(f"no frame {number}: frames are counted from 0")
506
610
  if number < len(times):
507
- found = self._seek_to_time(times[number])
611
+ found = self._seek_to_frame(number)
508
612
  else:
509
613
  # Frame times not known this far yet: learn them on the way, on this capture.
510
614
  if times:
511
- found = self._seek_to_time(times[-1])
615
+ found = self._seek_to_frame(len(times) - 1)
512
616
  else:
513
617
  self.seek(0)
514
- found = self._grab_time() is not None
618
+ found = self._grab()
515
619
  if found:
516
- times.append(self._cap.get(cv2.CAP_PROP_POS_MSEC))
620
+ times.append(self._grabbed_time)
517
621
  while found and len(times) <= number:
518
- at = self._grab_time()
519
- found = at is not None
622
+ found = self._grab()
520
623
  if found:
521
- times.append(at)
624
+ times.append(self._grabbed_time)
522
625
  if not found:
523
626
  raise IndexError(f"no frame {number}: the video has {len(times)} frames")
524
627
  frame = self._retrieve_rgb()
@@ -526,19 +629,14 @@ class VideoReader(_FrameSource):
526
629
  raise IndexError(f"frame {number} can't be decoded")
527
630
  return self._hand_out(frame)
528
631
 
529
- def _grab_time(self) -> Optional[float]:
530
- """Decode the next frame without converting it: its time in ms, or None at the end."""
531
- if not self._cap.grab():
532
- return None
533
- return self._cap.get(cv2.CAP_PROP_POS_MSEC)
534
-
535
- def _seek_to_time(self, target: float) -> bool:
536
- """Grab the frame whose time is *target* ms. False if the video ends first.
632
+ def _seek_to_frame(self, number: int) -> bool:
633
+ """Grab frame *number*, whose time is known. False if the video ends first.
537
634
 
538
635
  A seek can't be trusted to land on a frame, but the times OpenCV reports while
539
636
  decoding are the frames' own. So seek to a moment before the target (further
540
637
  back if the seek lands after it), then decode forward to the frame.
541
638
  """
639
+ target = self._times[number]
542
640
  back = 1000.0 # ms: one second covers the gap between keyframes in most files
543
641
  while True:
544
642
  from_start = target - back <= 0
@@ -546,24 +644,26 @@ class VideoReader(_FrameSource):
546
644
  self.seek(0)
547
645
  else:
548
646
  self._cap.set(cv2.CAP_PROP_POS_MSEC, target - back)
549
- at = self._grab_time()
550
- if at is None:
647
+ if not self._grab():
551
648
  return False
552
- if from_start or at <= target + _FRAME_TIME_SLACK_MS:
649
+ if from_start or self._grabbed_time <= target + _FRAME_TIME_SLACK_MS:
553
650
  break
554
651
  back *= 2
555
- while at < target - _FRAME_TIME_SLACK_MS:
556
- at = self._grab_time()
557
- if at is None:
652
+ while self._grabbed_time < target - _FRAME_TIME_SLACK_MS:
653
+ if not self._grab():
558
654
  return False
655
+ self._next = number + 1 # positioned by time, so the count is set, not trusted
559
656
  return True
560
657
 
561
658
  def __repr__(self):
562
659
  rate = "unknown fps" if self.fps is None else f"{self.fps:.2f}fps"
563
660
  count = "unknown length" if self.frames is None else f"{self.frames} frames"
564
- stride = "" if self._stride == 1 else f", stride={self._stride}"
661
+ if self._rate is not None:
662
+ sampling = f", rate={self._rate:g}"
663
+ else:
664
+ sampling = "" if self._stride == 1 else f", stride={self._stride}"
565
665
  return (f"VideoReader({self._source!r}, {self.width}x{self.height}, "
566
- f"{rate}, {count}{stride})")
666
+ f"{rate}, {count}{sampling})")
567
667
 
568
668
 
569
669
  class CameraStream(_FrameSource):
@@ -791,19 +891,20 @@ class VideoWriter:
791
891
  # ---------------------------------------------------------------------------
792
892
 
793
893
  def read_video(source: str, *, stride: int = 1, start: int = 0,
794
- width=_UNSET) -> "VideoReader":
894
+ rate: Optional[float] = None, width=_UNSET) -> "VideoReader":
795
895
  """Open a video file for frame-by-frame reading.
796
896
 
797
897
  Args:
798
898
  source: Path to a video file.
799
899
  stride: Yield every Nth frame.
800
900
  start: Frame to begin at.
901
+ rate: Yield this many frames a second instead, by the frames' own times.
801
902
 
802
903
  Returns:
803
904
  A VideoReader instance.
804
905
  """
805
906
  _reject_width(width, "read_video")
806
- return VideoReader(source, stride=stride, start=start)
907
+ return VideoReader(source, stride=stride, start=start, rate=rate)
807
908
 
808
909
 
809
910
  def read_image(source, width=_UNSET) -> np.ndarray:
@@ -902,8 +1003,39 @@ def read_image(source, width=_UNSET) -> np.ndarray:
902
1003
  return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
903
1004
 
904
1005
 
1006
+ def _to_bgr(image, suffix: str) -> np.ndarray:
1007
+ """Check an RGB or RGBA image against *suffix* and convert it for OpenCV.
1008
+
1009
+ RGBA is refused for a format outside ``_ALPHA_WRITABLE`` rather than flattened,
1010
+ which would mean choosing a background colour for the caller.
1011
+ """
1012
+ _require_rgb(image, "image", alpha=True)
1013
+ if image.shape[2] == 3:
1014
+ return cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
1015
+ if suffix.lower() not in _ALPHA_WRITABLE:
1016
+ formats = ", ".join(sorted(_ALPHA_WRITABLE))
1017
+ raise ValueError(
1018
+ f"Cannot encode an RGBA image as {suffix!r}: the format has no transparency. "
1019
+ f"Use one of {formats}, or drop the alpha with image[:, :, :3]."
1020
+ )
1021
+ return cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA)
1022
+
1023
+
1024
+ def _imencode(bgr: np.ndarray, suffix: str) -> bytes:
1025
+ """``cv2.imencode``, with an unknown format raised as a ValueError."""
1026
+ try:
1027
+ success, buffer = cv2.imencode(suffix, bgr)
1028
+ except cv2.error as error:
1029
+ raise ValueError(
1030
+ f"Cannot encode {suffix!r}: OpenCV does not support that format"
1031
+ ) from error
1032
+ if not success:
1033
+ raise ValueError(f"Failed to encode image as {suffix!r}")
1034
+ return buffer.tobytes()
1035
+
1036
+
905
1037
  def encode_image(image: np.ndarray, extension: str = ".png") -> bytes:
906
- """Encode an RGB image to bytes, for an HTTP response or a blob.
1038
+ """Encode an RGB or RGBA image to bytes, for an HTTP response or a blob.
907
1039
 
908
1040
  The mirror of ``read_image``'s buffer branch, and it exists for the same reason:
909
1041
  channel order is established at the codec boundary, so there has to be one
@@ -911,49 +1043,45 @@ def encode_image(image: np.ndarray, extension: str = ".png") -> bytes:
911
1043
  that goes with it, and that is the step that gets forgotten.
912
1044
 
913
1045
  Args:
914
- image: RGB uint8 array of shape (H, W, 3).
915
- extension: Container/format extension, with or without the dot.
1046
+ image: RGB uint8 array of shape (H, W, 3), or RGBA (H, W, 4), such as a
1047
+ cut-out from background removal.
1048
+ extension: Container/format extension, with or without the dot. An RGBA
1049
+ image needs one that keeps transparency: ``.png``, ``.webp``, ``.tif`` or
1050
+ ``.tiff``. WebP does not keep the colour of fully transparent pixels.
916
1051
 
917
1052
  Returns:
918
1053
  The encoded bytes.
919
1054
 
920
1055
  Raises:
921
- ValueError: If the image is not RGB uint8 HxWx3, or OpenCV cannot encode
1056
+ ValueError: If the image is not RGB or RGBA uint8, an RGBA image is given a
1057
+ format without transparency (such as ``.jpg``), or OpenCV cannot encode
922
1058
  the requested format.
923
1059
 
924
1060
  Example:
925
1061
  >>> payload = pf.encode_image(frame, ".jpg")
926
1062
  >>> return Response(payload, media_type="image/jpeg")
927
1063
  """
928
- _require_rgb(image, "image")
929
1064
  suffix = extension if extension.startswith(".") else f".{extension}"
930
-
931
- bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
932
- try:
933
- success, buffer = cv2.imencode(suffix, bgr)
934
- except cv2.error as error:
935
- raise ValueError(
936
- f"Cannot encode {suffix!r}: OpenCV does not support that format"
937
- ) from error
938
- if not success:
939
- raise ValueError(f"Failed to encode image as {suffix!r}")
940
- return buffer.tobytes()
1065
+ return _imencode(_to_bgr(image, suffix), suffix)
941
1066
 
942
1067
 
943
1068
  def save_image(path: str, image: np.ndarray) -> None:
944
- """Save an RGB numpy array to an image file.
1069
+ """Save an RGB or RGBA numpy array to an image file.
945
1070
 
946
1071
  Args:
947
1072
  path: Output file path (extension determines format).
948
- image: RGB numpy array.
1073
+ image: RGB uint8 array (H, W, 3), or RGBA (H, W, 4) for a format that keeps
1074
+ transparency: ``.png``, ``.webp``, ``.tif`` or ``.tiff``.
949
1075
 
950
1076
  Raises:
951
1077
  NotADirectoryError: If the parent directory does not exist.
952
- ValueError: If the image is not RGB uint8 HxWx3, or the extension is
1078
+ ValueError: If the image is not RGB or RGBA uint8, an RGBA image is given a
1079
+ format without transparency (such as ``.jpg``), or the extension is
953
1080
  missing or not one OpenCV can write.
954
1081
  OSError: If the file cannot be written for any other reason.
955
1082
  """
956
- _require_rgb(image, "image")
1083
+ # Checked first, so a bad image is reported before a bad path, as it always was.
1084
+ _require_rgb(image, "image", alpha=True)
957
1085
  target = Path(path)
958
1086
 
959
1087
  # cv2.imwrite returns False for a missing directory and raises cv2.error for an
@@ -970,13 +1098,12 @@ def save_image(path: str, image: np.ndarray) -> None:
970
1098
  f"what format to encode. Try '{target.name}.jpg' or '{target.name}.png'."
971
1099
  )
972
1100
 
973
- # Encoding goes through encode_image rather than cv2.imwrite, so that the
974
- # RGB-to-BGR step and the frame guard exist once. A second encoder here would
975
- # be exactly the duplication encode_image was added to remove.
1101
+ # Encoding goes through the same steps as encode_image rather than cv2.imwrite,
1102
+ # so that the colour conversion and the checks exist once.
1103
+ bgr = _to_bgr(image, target.suffix)
976
1104
  try:
977
- payload = encode_image(image, target.suffix)
1105
+ payload = _imencode(bgr, target.suffix)
978
1106
  except ValueError as error:
979
- # The image was checked above, so anything left is the format.
980
1107
  raise ValueError(
981
1108
  f"Cannot write {path!r}: OpenCV cannot encode '{target.suffix}' files"
982
1109
  ) from error
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pixelflow
3
- Version: 0.8.0
3
+ Version: 0.10.0
4
4
  Summary: Computer vision processing library for visualizing and analyzing detection results from ML models
5
5
  Author-email: Emrah Nazif <emrah@datamarkin.com>
6
6
  License: Apache-2.0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes