Skip to content

Commit 0434097

Browse files
committed
Adding more examples
1 parent 4e03f3f commit 0434097

7 files changed

Lines changed: 333 additions & 0 deletions

File tree

basic-concepts/5b-builtin-function.py

Whitespace-only changes.

real-world-examples/digi_clock/digital_alarm.py

Whitespace-only changes.
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
from tkinter import *
2+
from tkinter.ttk import *
3+
import datetime
4+
import platform
5+
try:
6+
import winsound
7+
type='windows'
8+
except:
9+
import os
10+
type='other'
11+
window = Tk()
12+
window.title("Clock")
13+
window.geometry('500x250')
14+
stopwatch_counter_num = 66600
15+
stopwatch_running = False
16+
timer_counter_num = 66600
17+
timer_running = False
18+
def clock():
19+
date_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S/%p")
20+
date,time1 = date_time.split()
21+
time2,time3 = time1.split('/')
22+
hour,minutes,seconds = time2.split(':')
23+
if int(hour) > 11 and int(hour) < 24:
24+
time = str(int(hour) - 12) + ':' + minutes + ':' + seconds + ' ' + time3
25+
else:
26+
time = time2 + ' ' + time3
27+
time_label.config(text = time)
28+
date_label.config(text= date)
29+
time_label.after(1000, clock)
30+
def alarm():
31+
main_time = datetime.datetime.now().strftime("%H:%M %p")
32+
alarm_time = get_alarm_time_entry.get()
33+
alarm_time1,alarm_time2 = alarm_time.split(' ')
34+
alarm_hour, alarm_minutes = alarm_time1.split(':')
35+
main_time1,main_time2 = main_time.split(' ')
36+
main_hour1, main_minutes = main_time1.split(':')
37+
if main_time2 == 'PM':
38+
main_hour = str(int(main_hour1) - 12)
39+
else:
40+
main_hour = main_hour1
41+
if int(alarm_hour) == int(main_hour) and int(alarm_minutes) == int(main_minutes) and main_time2 == alarm_time2:
42+
for i in range(3):
43+
alarm_status_label.config(text='Time Is Up')
44+
if platform.system() == 'Windows':
45+
winsound.Beep(5000,1000)
46+
elif platform.system() == 'Darwin':
47+
os.system('say Time is Up')
48+
elif platform.system() == 'Linux':
49+
os.system('beep -f 5000')
50+
get_alarm_time_entry.config(state='enabled')
51+
set_alarm_button.config(state='enabled')
52+
get_alarm_time_entry.delete(0,END)
53+
alarm_status_label.config(text = '')
54+
else:
55+
alarm_status_label.config(text='Alarm Has Started')
56+
get_alarm_time_entry.config(state='disabled')
57+
set_alarm_button.config(state='disabled')
58+
alarm_status_label.after(1000, alarm)
59+
def stopwatch_counter(label):
60+
def count():
61+
if stopwatch_running:
62+
global stopwatch_counter_num
63+
if stopwatch_counter_num==66600:
64+
display="Starting..."
65+
else:
66+
tt = datetime.datetime.fromtimestamp(stopwatch_counter_num)
67+
string = tt.strftime("%H:%M:%S")
68+
display=string
69+
label.config(text=display)
70+
label.after(1000, count)
71+
stopwatch_counter_num += 1
72+
count()
73+
def stopwatch(work):
74+
if work == 'start':
75+
global stopwatch_running
76+
stopwatch_running=True
77+
stopwatch_start.config(state='disabled')
78+
stopwatch_stop.config(state='enabled')
79+
stopwatch_reset.config(state='enabled')
80+
stopwatch_counter(stopwatch_label)
81+
elif work == 'stop':
82+
stopwatch_running=False
83+
stopwatch_start.config(state='enabled')
84+
stopwatch_stop.config(state='disabled')
85+
stopwatch_reset.config(state='enabled')
86+
elif work == 'reset':
87+
global stopwatch_counter_num
88+
stopwatch_running=False
89+
stopwatch_counter_num=66600
90+
stopwatch_label.config(text='Stopwatch')
91+
stopwatch_start.config(state='enabled')
92+
stopwatch_stop.config(state='disabled')
93+
stopwatch_reset.config(state='disabled')
94+
def timer_counter(label):
95+
def count():
96+
global timer_running
97+
if timer_running:
98+
global timer_counter_num
99+
if timer_counter_num==66600:
100+
for i in range(3):
101+
display="Time Is Up"
102+
if platform.system() == 'Windows':
103+
winsound.Beep(5000,1000)
104+
elif platform.system() == 'Darwin':
105+
os.system('say Time is Up')
106+
elif platform.system() == 'Linux':
107+
os.system('beep -f 5000')
108+
timer_running=False
109+
timer('reset')
110+
else:
111+
tt = datetime.datetime.fromtimestamp(timer_counter_num)
112+
string = tt.strftime("%H:%M:%S")
113+
display=string
114+
timer_counter_num -= 1
115+
label.config(text=display)
116+
label.after(1000, count)
117+
count()
118+
def timer(work):
119+
if work == 'start':
120+
global timer_running, timer_counter_num
121+
timer_running=True
122+
if timer_counter_num == 66600:
123+
timer_time_str = timer_get_entry.get()
124+
hours,minutes,seconds=timer_time_str.split(':')
125+
minutes = int(minutes) + (int(hours) * 60)
126+
seconds = int(seconds) + (minutes * 60)
127+
timer_counter_num = timer_counter_num + seconds
128+
timer_counter(timer_label)
129+
timer_start.config(state='disabled')
130+
timer_stop.config(state='enabled')
131+
timer_reset.config(state='enabled')
132+
timer_get_entry.delete(0,END)
133+
elif work == 'stop':
134+
timer_running=False
135+
timer_start.config(state='enabled')
136+
timer_stop.config(state='disabled')
137+
timer_reset.config(state='enabled')
138+
elif work == 'reset':
139+
timer_running=False
140+
timer_counter_num=66600
141+
timer_start.config(state='enabled')
142+
timer_stop.config(state='disabled')
143+
timer_reset.config(state='disabled')
144+
timer_get_entry.config(state='enabled')
145+
timer_label.config(text = 'Timer')
146+
tabs_control = Notebook(window)
147+
clock_tab = Frame(tabs_control)
148+
alarm_tab = Frame(tabs_control)
149+
stopwatch_tab = Frame(tabs_control)
150+
timer_tab = Frame(tabs_control)
151+
tabs_control.add(clock_tab, text="Clock")
152+
tabs_control.add(alarm_tab, text="Alarm")
153+
tabs_control.add(stopwatch_tab, text='Stopwatch')
154+
tabs_control.add(timer_tab, text='Timer')
155+
tabs_control.pack(expand = 1, fill ="both")
156+
time_label = Label(clock_tab, font = 'calibri 40 bold', foreground = 'black')
157+
time_label.pack(anchor='center')
158+
date_label = Label(clock_tab, font = 'calibri 40 bold', foreground = 'black')
159+
date_label.pack(anchor='s')
160+
get_alarm_time_entry = Entry(alarm_tab, font = 'calibri 15 bold')
161+
get_alarm_time_entry.pack(anchor='center')
162+
alarm_instructions_label = Label(alarm_tab, font = 'calibri 10 bold', text = "Enter Alarm Time. Eg -> 01:30 PM, 01 -> Hour, 30 -> Minutes")
163+
alarm_instructions_label.pack(anchor='s')
164+
set_alarm_button = Button(alarm_tab, text = "Set Alarm", command=alarm)
165+
set_alarm_button.pack(anchor='s')
166+
alarm_status_label = Label(alarm_tab, font = 'calibri 15 bold')
167+
alarm_status_label.pack(anchor='s')
168+
stopwatch_label = Label(stopwatch_tab, font='calibri 40 bold', text='Stopwatch')
169+
stopwatch_label.pack(anchor='center')
170+
stopwatch_start = Button(stopwatch_tab, text='Start', command=lambda:stopwatch('start'))
171+
stopwatch_start.pack(anchor='center')
172+
stopwatch_stop = Button(stopwatch_tab, text='Stop', state='disabled',command=lambda:stopwatch('stop'))
173+
stopwatch_stop.pack(anchor='center')
174+
stopwatch_reset = Button(stopwatch_tab, text='Reset', state='disabled', command=lambda:stopwatch('reset'))
175+
stopwatch_reset.pack(anchor='center')
176+
timer_get_entry = Entry(timer_tab, font='calibiri 15 bold')
177+
timer_get_entry.pack(anchor='center')
178+
timer_instructions_label = Label(timer_tab, font = 'calibri 10 bold', text = "Enter Timer Time. Eg -> 01:30:30, 01 -> Hour, 30 -> Minutes, 30 -> Seconds")
179+
timer_instructions_label.pack(anchor='s')
180+
timer_label = Label(timer_tab, font='calibri 40 bold', text='Timer')
181+
timer_label.pack(anchor='center')
182+
timer_start = Button(timer_tab, text='Start', command=lambda:timer('start'))
183+
timer_start.pack(anchor='center')
184+
timer_stop = Button(timer_tab, text='Stop', state='disabled',command=lambda:timer('stop'))
185+
timer_stop.pack(anchor='center')
186+
timer_reset = Button(timer_tab, text='Reset', state='disabled', command=lambda:timer('reset'))
187+
timer_reset.pack(anchor='center')
188+
clock()
189+
window.mainloop()

real-world-examples/digi_clock/digital_stopwatch.py

Whitespace-only changes.

real-world-examples/digi_clock/digital_timer.py

Whitespace-only changes.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# importing libraries
2+
# pip install opencv-python
3+
import cv2
4+
import numpy as np
5+
6+
# reading image
7+
img = cv2.imread("jassi.jpg")
8+
9+
# Edges
10+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
11+
gray = cv2.medianBlur(gray, 5)
12+
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
13+
cv2.THRESH_BINARY, 9, 5)
14+
15+
# Cartoonization
16+
color = cv2.bilateralFilter(img, 9, 200, 200)
17+
cartoon = cv2.bitwise_and(color, color, mask=edges)
18+
19+
#cv2.imshow("Image", img)
20+
#cv2.imshow("edges", edges)
21+
cv2.imshow("Cartoon", cartoon)
22+
23+
24+
color = cv2.bilateralFilter(img, d=9, sigmaColor=200,sigmaSpace=200)
25+
cv2.imshow("Color", color)
26+
27+
def color_quantization(img, k):
28+
# Defining input data for clustering
29+
data = np.float32(img).reshape((-1, 3))
30+
# Defining criteria
31+
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
32+
# Applying cv2.kmeans function
33+
ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
34+
center = np.uint8(center)
35+
result = center[label.flatten()]
36+
result = result.reshape(img.shape)
37+
return result
38+
39+
img_1 = color_quantization(img, 9)
40+
cv2.imshow("Quant", img_1)
41+
cv2.waitKey(0)
42+
cv2.destroyAllWindows()
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Importing the required modules
2+
import tkinter as tk # graphical user interface toolkit
3+
from tkinter import *
4+
import easygui # to open the filebox
5+
import cv2 # for image processing
6+
import matplotlib.pyplot as plt
7+
8+
import os # to read and save path
9+
import sys #
10+
11+
# Making the GUI main window
12+
top = tk.Tk()
13+
top.geometry('400x400')
14+
top.title('Cartoonify Your Image !')
15+
top.configure(background='blue')
16+
label = Label(top, background='#CDCDCD', font=('calibri', 20, 'bold'))
17+
18+
""" fileopenbox opens the box to choose file
19+
and help us store file path as string"""
20+
21+
22+
def upload():
23+
image_path = easygui.fileopenbox()
24+
cartoonify(image_path)
25+
26+
27+
# Step 3: How is an image stored?
28+
def cartoonify(image_path):
29+
# read image
30+
original_image = cv2.imread(image_path)
31+
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
32+
print(original_image) # this will be stored in form of number
33+
34+
# to confirm it is image that was chosing
35+
if original_image is None:
36+
print("Can't find any image. Choose appropriate file")
37+
sys.exit()
38+
resize_image1 = cv2.resize(original_image, (960, 540))
39+
# plt.imshow(resize_image1, cmap='gray')
40+
41+
# converting an image to grayscale
42+
grayscale_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
43+
resize_image2 = cv2.resize(grayscale_image, (960, 540))
44+
# plt.imshow(resize_image2, cmap="gray")
45+
46+
# applying median blur to smoothen an image
47+
smooth_grayscale_image = cv2.medianBlur(grayscale_image, 5)
48+
resize_image3 = cv2.resize(smooth_grayscale_image, (960, 540))
49+
# plt.imshow(resize_image3, cmap='gray')
50+
51+
# retrieving the edges for cartoon effect
52+
# by using thresholding technique
53+
get_edge = cv2.adaptiveThreshold(smooth_grayscale_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
54+
resize_image4 = cv2.resize(get_edge, (960, 540))
55+
# plt.imshow(resize_image4, cmap='gray')
56+
57+
# applying bilateral filter to remove noise
58+
# and keep edge sharp as required
59+
color_image = cv2.bilateralFilter(original_image, 9, 300, 300)
60+
resize_image5 = cv2.resize(color_image, (960, 540))
61+
# plt.imshow(resize_image5, cmap="gray")
62+
63+
# masking edged image with our "BEAUTIFY" image
64+
cartoon_image = cv2.bitwise_and(color_image, color_image, mask=get_edge)
65+
resize_image6 = cv2.resize(cartoon_image, (960, 540))
66+
# plt.imshow(resize_image6, cmap='gray')
67+
68+
# Plotting the whole transition
69+
images = [resize_image1, resize_image2, resize_image3, resize_image4, resize_image5, resize_image6]
70+
fig, axes = plt.subplots(3, 2, figsize=(8, 8), subplot_kw={'xticks': [], 'yticks': []},
71+
gridspec_kw=dict(hspace=0.1, wspace=0.1))
72+
for i, ax in enumerate(axes.flat):
73+
ax.imshow(images[i], cmap='gray')
74+
75+
# Making a Save button in the GUI main window
76+
savel = Button(top, text="Save cartoon image", command=lambda: save(resize_image6, image_path), padx=30, pady=5)
77+
savel.configure(background='#364156', foreground='white', font=('calibri', 10, 'bold'))
78+
savel.pack(side=TOP, pady=50)
79+
80+
# save button code
81+
plt.show()
82+
83+
84+
def save(resize_image6, image_path):
85+
# saving an image using imwrite function
86+
new_name = "cartoonified_Image"
87+
path1 = os.path.dirname(image_path)
88+
extension = os.path.splitext(image_path)[1]
89+
path = os.path.join(path1, new_name + extension)
90+
cv2.imwrite(path, cv2.cvtColor(resize_image6, cv2.COLOR_RGB2BGR))
91+
I = "Image saved by name " + new_name + " at " + path
92+
tk.messagebox.showinfo(title=None, message=I)
93+
94+
95+
# Making the Cartoonify button in the GUI main window
96+
upload = Button(top, text="Cartoonify an Image", command=upload, padx=10, pady=5)
97+
upload.configure(background="#374256", foreground="wheat", font=('calibri', 10, 'bold'))
98+
upload.pack(side=TOP, pady=50)
99+
100+
# Main function to build the GUI window
101+
top.mainloop()
102+
{"mode":"full","isActive":false}

0 commit comments

Comments
 (0)