-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample4.py
More file actions
51 lines (38 loc) · 1.67 KB
/
example4.py
File metadata and controls
51 lines (38 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Edge Detection Example
# Original Sketch from Processing's Topics/ImageProcessing/EdgeDetection Example code
#
# In this adaptation of Processing's Edge Detection example, OpenCV is used to
# perform the edge detection. The edge detection mode can be changed by pressing
# 't' for tight, 'w' for wide, or any other key for auto.
#
# Canny edge detection algorithm adapted from:
# https://pyimagesearch.com/2015/04/06/zero-parameter-automatic-canny-edge-detection-with-python-and-opencv/
import traceback
import numpy as np
import cv2
from jpype import JClass
import py5_tools
import py5
def filter_image(img: py5.Py5Image, img_filtered: py5.Py5Image, mode: str):
try:
img.load_np_pixels()
if mode == 'auto':
sigma = 0.33
median = np.median(img.np_pixels)
lower_limit = int(max(0, (1 - sigma) * median))
upper_limit = int(min(255, (1 + sigma) * median))
elif mode == 'tight':
lower_limit, upper_limit = 225, 250
elif mode == 'wide':
lower_limit, upper_limit = 10, 200
img_array_gray = cv2.cvtColor(img.np_pixels, cv2.COLOR_BGR2GRAY)
img_array_blurred = cv2.GaussianBlur(img_array_gray, (5, 5), 0)
img_array_edges = cv2.Canny(
img_array_blurred, lower_limit, upper_limit)
img_filtered.set_np_pixels(img_array_edges, bands='L')
except Exception as e:
traceback.print_exc()
return JClass('java.lang.RuntimeException')(str(e))
py5_tools.register_processing_mode_key("filter_image", filter_image)
# run the sketch in processing mode, specifying the Java class to instantiate
py5.run_sketch(jclassname='test.Example4Sketch')