Cartooning Image#

import cv2
import numpy as np
import matplotlib.pyplot as plt

Load Gambar#

Fungsi Load Gambar#

def read_file(filename):
  img = cv2.imread(filename)
  img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
  plt.imshow(img)
  plt.show()
  return img

Menampilkan Gambar#

filename = "/content/drive/MyDrive/DeepLearning/Cartooning/tugas/karapan_sapi.jpg"
img = read_file(filename)
_images/05a4718f5da00fbdf4ba5c3c48a62df426c7f7027448d34e621af197c3312a4f.png

Membuat Batas Tepian#

Fungsi Batas Tepian#

def edge_mask(img,line_size,blur_value):
  gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
  gray_blur = cv2.medianBlur(gray, blur_value)
  edges = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY, line_size, blur_value)
  return edges

Menampilkan hasil Batas Tepian#

line_size = 11
blur_value = 5
edges = edge_mask(img,line_size,blur_value)

plt.imshow(edges,cmap = "gray")
plt.show()
_images/8c49bac48cdf00d1d410d031c6b072db41182b1d57d2f9ac6f698b2d76d923eb.png

Mengurangi Warna Pallete#

Fungsi Warna Pallete#

def color_quantization(img,k):
  data = np.float32(img).reshape((-1,3))
  criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,20,0.001)
  ret,label,center = cv2.kmeans(data,k,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
  center = np.uint8(center)

  result = center[label.flatten()]
  result = result.reshape(img.shape)
  return result

Menampilkan hasil pengurangan warna palette#

img_quantization = color_quantization(img,k=15)
plt.imshow(img_quantization)
plt.show()

Mengurangi noise#

Fungsi Pengurangan Noise pada gambar#

blurred = cv2.bilateralFilter(img_quantization, d= 20, sigmaColor = 200, sigmaSpace = 200)
plt.imshow(blurred)
plt.show()
_images/4b7d42da478eeb36f1df1dc2749d03ff3b1d0c31ae190bd18b12d0524944954b.png

Cartooning Gambar#

Fungsi Cartooning Gmbar#

def cartoon():
  c = cv2.bitwise_and(blurred, blurred,mask = edges)
  return c

Menampilkan gambar cartooning#

img_cartoon = cartoon()
plt.imshow(img_cartoon)
plt.title("gambar cartoon")
plt.show()
_images/71126c6ad624d2abe137d3bf264302efcc5a0188e925b1148e7449472880a5ee.png