Skip to content

Commit

Permalink
Merge pull request #6 from svohara/black-format
Browse files Browse the repository at this point in the history
Black formatting applied to entire repo.
  • Loading branch information
svohara authored Apr 28, 2020
2 parents a880fa5 + bf5afcc commit 21cdb84
Show file tree
Hide file tree
Showing 29 changed files with 633 additions and 333 deletions.
21 changes: 14 additions & 7 deletions examples/annotate_an_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ def annotation_demo():
img.annotate_point((300, 300)) # default color is red

# annotate text next to the brown point, blue on white background
img.annotate_text("Waldo was here", (254, 246),
color=pv3.RGB_BLUE,
bg_color=pv3.RGB_WHITE)
img.annotate_text(
"Waldo was here", (254, 246), color=pv3.RGB_BLUE, bg_color=pv3.RGB_WHITE
)

# complex polygon with an exterior and an interior 'hole'
exterior = ((50, 50), (25, 125), (50, 200), (200, 200), (200, 50), (50, 50))
Expand All @@ -30,21 +30,28 @@ def annotation_demo():

# two concentric circles
img.annotate_circle((400, 400), 75, color=pv3.RGB_PURPLE, thickness=5)
img.annotate_circle((400, 400), 60, color=pv3.RGB_PURPLE, thickness=-1) # filled circle
img.annotate_circle(
(400, 400), 60, color=pv3.RGB_PURPLE, thickness=-1
) # filled circle

# a LineString
lines = sg.LineString(((10, 25), (382, 122), (251, 470)))
img.annotate_shape(lines, thickness=4, color=pv3.RGB_RED)

# a Rectangle
img.annotate_rect((538, 212), (600, 300), color=pv3.RGB_ORANGE, thickness=3) # -1 for filled
img.annotate_rect(
(538, 212), (600, 300), color=pv3.RGB_ORANGE, thickness=3
) # -1 for filled

# show the image with annotations
# NOTE: to NOT show the annotations, set annotations=False in the following
# img.show_annotation(window_title="Mask Layer", highgui=True, delay=1)
img.show(window_title="Annotated Image", highgui=True, delay=0, annotations_opacity=0.5)
img.show(
window_title="Annotated Image", highgui=True, delay=0, annotations_opacity=0.5
)

if __name__ == '__main__':

if __name__ == "__main__":
print("====================================================")
print("Set focus to display window and hit any key to exit.")
print("====================================================")
Expand Down
16 changes: 7 additions & 9 deletions examples/bg_subtract_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,16 @@ def demo():
am_key = ib.last()

# display result side-by-side with key image to which it applies
img_list = [fd_key, fd_mask,
md_key, md_mask,
am_key, am_mask]
img_lbls = ["FD: Img", "FD: Mask",
"MD: Img", "MD: Mask",
"AM: Img", "AM: Mask"]
imontage = pv3.ImageMontage(img_list, layout=(3, 2), tile_size=(320, 240),
labels=img_lbls)
img_list = [fd_key, fd_mask, md_key, md_mask, am_key, am_mask]
img_lbls = ["FD: Img", "FD: Mask", "MD: Img", "MD: Mask", "AM: Img", "AM: Mask"]
imontage = pv3.ImageMontage(
img_list, layout=(3, 2), tile_size=(320, 240), labels=img_lbls
)
imontage.show(window_title="Background Subtraction", delay=0)
return bg

if __name__ == '__main__':

if __name__ == "__main__":
print("=================================================================")
print("Focus on montage image, and hit any key to exit.")
print("=================================================================")
Expand Down
10 changes: 7 additions & 3 deletions examples/crop_regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,20 @@ def demo():
# Labels for the montage are the upper left corner of the cropped area
neg_crops = pv3.crop_negative_regions(img, [p_cat], (150, 150), N=10)
nc_labels = [str(c.metadata["crop_bounds"][0:2]) for c in neg_crops]
montage3 = pv3.ImageMontage(neg_crops, layout=(2, 5), tile_size=(150, 150), labels=nc_labels)
montage3 = pv3.ImageMontage(
neg_crops, layout=(2, 5), tile_size=(150, 150), labels=nc_labels
)
mnt_image_negs = montage3.as_image()

mnt_image.show(window_title="Crops from bounding boxes", delay=1, pos=(10, 10))
mnt_image2.show(window_title="Crops from centroids and fixed size", delay=1, pos=(10, 200))
mnt_image2.show(
window_title="Crops from centroids and fixed size", delay=1, pos=(10, 200)
)
mnt_image_negs.show(window_title="Random background crops", delay=0, pos=(10, 400))
img.imshow(window_title="Source image and regions")


if __name__ == '__main__':
if __name__ == "__main__":
print("=================================================================")
print("Demonstrating extracting crops from a source image")
print("Focus on either montage image, and hit any key to exit.")
Expand Down
26 changes: 17 additions & 9 deletions examples/image_montage_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,32 @@ def main():
Demonstrates several annotation methods of the Image class
"""
img1 = pv3.Image(pv3.IMG_DRIVEWAY)
img1.annotate_text("sample annotation", (200, 200), color=pv3.RGB_CYAN, bg_color=pv3.RGB_BLACK, font_scale=2)
img1.annotate_text(
"sample annotation",
(200, 200),
color=pv3.RGB_CYAN,
bg_color=pv3.RGB_BLACK,
font_scale=2,
)
img2 = pv3.Image(pv3.IMG_PRIUS)
img3 = pv3.Image(pv3.IMG_SLEEPYCAT)
img_list = [img1, img2, img3] * 4
imontage = pv3.ImageMontage(img_list,
layout=(1, 3),
tile_size=(480, 360),
labels="index",
keep_aspect=True,
highlight_selected=True,
alpha=0.6)
imontage = pv3.ImageMontage(
img_list,
layout=(1, 3),
tile_size=(480, 360),
labels="index",
keep_aspect=True,
highlight_selected=True,
alpha=0.6,
)
imontage.show() # event loop, blocks until user quits montage
sel = imontage.get_highlighted()
sel_str = ",".join([str(x) for x in sel])
print("You selected these images: {}".format(sel_str))


if __name__ == '__main__':
if __name__ == "__main__":
print("====================================================")
print("Click on some of the image tiles in the montage")
print("With montage window in focus, hit spacebar to quit")
Expand Down
10 changes: 7 additions & 3 deletions examples/image_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,20 @@ def demo():
tiles2 = pv3.crop_negative_regions(img, poly_list, crop_size=(150, 150), N=15)

# combine drawn tiles and random tiles and shuffle together
all_tiles = [(idx, tile) for (idx, tile) in enumerate(tiles+tiles2)]
all_tiles = [(idx, tile) for (idx, tile) in enumerate(tiles + tiles2)]
random.shuffle(all_tiles) # modifies list in-place

print("=================================================================")
print("STEP 3: Use tile selector to select the tiles you created, ")
print(" not the random crops...if you can! After selecting the tiles")
print(" on a page, hit the space bar to go to the next page.")
print("=================================================================")
tile_generator = ((str(id), tile, "label_{}".format(id)) for (id, tile) in all_tiles)
ts = pv3.TileSelector(tile_generator, chunk_size=8, layout=(2, 4), tile_size=(150, 150))
tile_generator = (
(str(id), tile, "label_{}".format(id)) for (id, tile) in all_tiles
)
ts = pv3.TileSelector(
tile_generator, chunk_size=8, layout=(2, 4), tile_size=(150, 150)
)
ts.process_all()
selected_tiles = sorted(ts.selected)

Expand Down
18 changes: 9 additions & 9 deletions examples/inset_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


def _fake_data(k):
bar_chart_vals = 3*np.random.rand(k) + 8
bar_chart_vals = 3 * np.random.rand(k) + 8
line_plot_vals = np.random.randint(8000, 9300, k)
return [bar_chart_vals, line_plot_vals]

Expand All @@ -27,17 +27,17 @@ def _plot_data(dat):
fig = plt.figure(figsize=(8, 1), dpi=100) # 800x100 pixel plot
plt.bar(x_vals, bar_vals)
ax1 = plt.gca()
ax1.set_ylabel('mice')
ax1.set_ylabel("mice")
ax1.set_ylim([5, 15])

ax1.tick_params('y', colors='b')
ax1.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
ax1.tick_params("y", colors="b")
ax1.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=False)

ax2 = ax1.twinx()
ax2.plot(x_vals, line_vals, 'r-')
ax2.set_ylabel('purring')
ax2.plot(x_vals, line_vals, "r-")
ax2.set_ylabel("purring")
ax2.set_ylim([7000, 9500])
ax2.tick_params('y', colors='r')
ax2.tick_params("y", colors="r")

return fig

Expand All @@ -54,13 +54,13 @@ def main():
overlay = _get_inset_image(20)

x_pos = 5
y_pos = img.size[1]-overlay.size[1]-5
y_pos = img.size[1] - overlay.size[1] - 5

img.annotate_inset_image(overlay, (x_pos, y_pos), size=None)
img.show(annotations_opacity=0.8)


if __name__ == '__main__':
if __name__ == "__main__":
print("====================================================")
print("With image window in focus, hit spacebar to quit")
print("====================================================")
Expand Down
30 changes: 21 additions & 9 deletions examples/inset_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,30 @@ def on_frame(frame, num, background_img=None, **kwargs):
callback function, called by vid.play(...) on
each new frame of the video
"""
assert(background_img is not None)
assert background_img is not None
img_w, img_h = background_img.size
inset_width = 225
inset_height = 150
inset_x = img_w - inset_width - 10
inset_y = img_h - inset_height - 10
background_img.annotate_inset_image(frame, pos=(inset_x, inset_y), size=(inset_width, inset_height))
background_img.annotate_text("{}".format(str(num).zfill(5)), (10, 10),
color=pv3.RGB_WHITE, bg_color=pv3.RGB_BLACK)
background_img.show(window_title="Picture-in-picture", delay=5, annotations_opacity=1.0)
background_img.annotate_rect((inset_x-2, inset_y-2),
(inset_x+inset_width+2, inset_y+inset_height+2),
color=pv3.RGB_BLACK, thickness=-1)
background_img.annotate_inset_image(
frame, pos=(inset_x, inset_y), size=(inset_width, inset_height)
)
background_img.annotate_text(
"{}".format(str(num).zfill(5)),
(10, 10),
color=pv3.RGB_WHITE,
bg_color=pv3.RGB_BLACK,
)
background_img.show(
window_title="Picture-in-picture", delay=5, annotations_opacity=1.0
)
background_img.annotate_rect(
(inset_x - 2, inset_y - 2),
(inset_x + inset_width + 2, inset_y + inset_height + 2),
color=pv3.RGB_BLACK,
thickness=-1,
)


def demo():
Expand All @@ -34,7 +45,8 @@ def demo():
delay=1,
on_new_frame=on_frame, # this will take care of output
background_img=img, # kwarg passed to on_frame
start_frame=250)
start_frame=250,
)


if __name__ == "__main__":
Expand Down
25 changes: 18 additions & 7 deletions examples/motion_detect_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ def each_frame(cur_frame, frame_num, key=None, image_buffer=None, motion=None):
out = motion.annotate_frame(convex_hull_color=None)
fg = motion.foreground_pixels()
if (out is not None) and (fg is not None):
montage = pv3.ImageMontage([out, fg], layout=(1, 2), tile_size=(320, 240),
labels=['Annotation', 'Foreground Pix'])
montage = pv3.ImageMontage(
[out, fg],
layout=(1, 2),
tile_size=(320, 240),
labels=["Annotation", "Foreground Pix"],
)
out_img = montage.as_image()
out_img.show(window_title="Motion Detection", delay=1)

Expand All @@ -27,7 +31,9 @@ def md_factory_static(vid):


def md_factory_approx_median():
md = pv3.MotionDetector(method=pv3.BG_SUBTRACT_APPROX_MEDIAN, buff_size=60, thresh=80)
md = pv3.MotionDetector(
method=pv3.BG_SUBTRACT_APPROX_MEDIAN, buff_size=60, thresh=80
)
return md


Expand All @@ -50,10 +56,15 @@ def demo():
# md = md_factory_n_frame_diff()
# md = md_factory_median()

vid.play(window_title=None, annotate=False,
start_frame=100, end_frame=1000,
on_new_frame=each_frame, motion=md)
vid.play(
window_title=None,
annotate=False,
start_frame=100,
end_frame=1000,
on_new_frame=each_frame,
motion=md,
)


if __name__ == '__main__':
if __name__ == "__main__":
demo()
2 changes: 1 addition & 1 deletion examples/play_webcam.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def play_sample_mov():
vid.play()


if __name__ == '__main__':
if __name__ == "__main__":
print("=================================================================")
print("Webcam video will start paused.")
print("With focus on video window, use the keyboard to control playback.")
Expand Down
57 changes: 45 additions & 12 deletions pyvision3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,65 @@
# addressing issues with matplotlib on osx/darwin, conda packaging?
try:
from sys import platform as sys_pf
if sys_pf == 'darwin':

if sys_pf == "darwin":
import matplotlib

matplotlib.use("TkAgg")
except ImportError:
print("Optional Matplotlib not installed. Matplotlib integration will not work.")

from .constants import *
from .pv_exceptions import *
from .geometry import Point, Rect, CenteredRect, in_bounds, integer_bounds, integer_coords_array
from .geometry import (
Point,
Rect,
CenteredRect,
in_bounds,
integer_bounds,
integer_coords_array,
)
from .image import Image, matplot_fig_to_image
from .affine import AffineTransformer, AffineRotation, AffineTranslate
from .imagebuffer import ImageBuffer
from .video import VideoInterface, Video, VideoFromFileList, VideoFromDir, VideoFromImageStack
from .video import (
VideoInterface,
Video,
VideoFromFileList,
VideoFromDir,
VideoFromImageStack,
)
from .montage import ImageMontage, VideoMontage

from pyvision3.video_proc.backgroundsubtract import \
FrameDifferenceModel, MedianModel, ApproximateMedianModel, AbstractBGModel, StaticModel, \
BG_SUBTRACT_STATIC, BG_SUBTRACT_FRAME_DIFF, BG_SUBTRACT_MEDIAN, BG_SUBTRACT_APPROX_MEDIAN
from pyvision3.video_proc.motiondetection import \
MotionDetector, MD_BOUNDING_RECTS, MD_STANDARDIZED_RECTS
from pyvision3.video_proc.backgroundsubtract import (
FrameDifferenceModel,
MedianModel,
ApproximateMedianModel,
AbstractBGModel,
StaticModel,
BG_SUBTRACT_STATIC,
BG_SUBTRACT_FRAME_DIFF,
BG_SUBTRACT_MEDIAN,
BG_SUBTRACT_APPROX_MEDIAN,
)
from pyvision3.video_proc.motiondetection import (
MotionDetector,
MD_BOUNDING_RECTS,
MD_STANDARDIZED_RECTS,
)

from pyvision3.dataset_tools.crops import crop_regions, crop_negative_regions, random_rect_gen
from pyvision3.dataset_tools.tile_selection import TileSelector, \
tiles_from_dir, tiles_from_files, tiles_from_vid
from pyvision3.dataset_tools.crops import (
crop_regions,
crop_negative_regions,
random_rect_gen,
)
from pyvision3.dataset_tools.tile_selection import (
TileSelector,
tiles_from_dir,
tiles_from_files,
tiles_from_vid,
)
from pyvision3.dataset_tools.capture_clicks import CaptureClicks
from pyvision3.dataset_tools.capture_polygons import CapturePolygons

__version__ = ".".join([str(x) for x in VERSION_TUPLE])

Loading

0 comments on commit 21cdb84

Please sign in to comment.