Skip to content

Commit a314adc

Browse files
committed
Added opencv2 examples
1 parent 247b320 commit a314adc

4 files changed

Lines changed: 183 additions & 1 deletion

File tree

.gitignore

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ __pycache__/
55
*.py[cod]
66
*$py.class
77

8+
# jpg, pngm jpeg
9+
*.jpg
10+
*.png
11+
*.jpeg
12+
813
# C extensions
914
*.so
1015

@@ -117,4 +122,4 @@ venv.bak/
117122
!requirements.txt
118123

119124
# Ignore mp3
120-
*.mp3
125+
*.mp3
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# capture single image from webcam using python
2+
3+
# importing OpenCV library
4+
# pip3 install opencv-python
5+
import cv2 as cv
6+
import time
7+
8+
# initialize the camera
9+
cam_port = 0
10+
cam = cv.VideoCapture(cam_port)
11+
12+
# wait for 2 seconds to adjust the camera lights, else picture will be always dark
13+
time.sleep(2)
14+
15+
# reading the input using the camera
16+
result, image = cam.read()
17+
18+
# If image will detected without any error, show result
19+
if result:
20+
21+
# showing result, it take frame name and image output
22+
cv.imshow("My Cam Pic", image)
23+
24+
# saving image in local storage
25+
cv.imwrite("cam_capture.jpg", image)
26+
27+
# If keyboard interrupt occurs, destroy image window
28+
cv.waitKey(0)
29+
cv.destroyWindow("My Cam Pic")
30+
31+
# If captured image is corrupted, moving to else part
32+
else:
33+
print("No image detected. Please! try again")
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)