You are on page 1of 10

THI/’C HI$N XÚ LÉ DÚ LI$U 2 CHIEU (ÂNH)

VÓI OPENCV
import numpy
as np import
cv2
import
imutils
import
glob
import os
from PIL import
Image from io
import BytesIO
import requests
import matplotlib.pyplot as plt

from google.colab import drive


drive.mount('/content/gdrive',force_remount=True)

# folder path =
"/content/gdrive/MyDrive/nhanDienDT/opencv/anhChan
Dung/acd*"

# # lay danh sách các têp anh trong thu muc và sap
xêp chúng theo thú tu can thiêt
# files = sorted(glob.glob(folder_path))

# # doc câc ânh vâ luu chung


vâo list images # images = []
# for file in files:
# image =
cv2.imread(file) #
if image is not
None:
# images.append(image)

# # hién thi câc ânh voi


plt.imshow # fig =
plt.figure(figsize=(10,
10)) # for i, image in
enumerate(images):
# ax = fig.add subplot(1, len(images), i+1)
# ax.imshow(cv2.cvtColor(image,
cv2.COLOR BGR2RGB)) # plt.show()

Làm mÕ ánh dúng GaussianBlur cúa OpenCV

image_folder

='/content/gdrive/MyDrive/nhanDienDT/opencv/anhCh

anDung/' images = os.listdir(image_folder)


for image_name in images:
image_path =

os.path.join(image_folder,

image_name) img =

cv2.imread(image_path)

# Ap dung Gaussian Blur


blurred = cv2.GaussianBlur(img, (5, 5), 0)

# Hien thi anh sau khi ap dung


Gaussian Blur plt.figure()
plt.imshow(cv2.cvtColor(blurred,
cv2.COLOR_BGR2RGB)) plt.axis('off')
plt.show()

Phát hien khuôn mat, vé khung, cat ánh

# Tao bô phân loai cascade dê phát hiên khuôn mãt


face classifier =
cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade frontalface alt2.xml')

# Lây danh sách tât ca các ành trong thu muc


images glob.glob(os.path.join(image_folder, "*"))

# Duyét qua tung ânh vâ phât


hién khuén mât for i, image
file in enumerate(images):
# Doc ânh
image = cv2.imread(image_file)

# Phát hiên khuôn màt trong ành


faces = face_classifier.detectMultiScale(image)

# Tao subplot vói hai côt


fig, axs = plt.subplots(1, 3, figsize=(15, 5))

# Hien thi ành goc


axs[0].imshow(cv2.cvtColor(image,
cv2.COLOR_BGR2RGB)) axs[0].set
title('Ánh Goc')
axs[0].axis('off')

# Duyét qua tung khuén mât vâ cat ânh theo


kich thuoc khuén mât for j, (x, y, w, h) in
enumerate(faces):
face image = image[y:y+h, x:x+w]

# # Luu khuôn mãt dã cat


thành têp tin mói # filename
= os.path.basename(image
file)
cv2.imwrite(f'/content/gdrive/MyDrive/nhanDienDT/
opencv/khuonMat/KhuonMat( i}(j+1}.jpg', face_image)

# Hién thi khuon mât kém khung bao


quanh
axs[1].imshow(cv2.cvtColor(image,
cv2.COLOR_BGR2RGB)) axs[1].set
title('Khung Bao Quanh')
axs[1].axis('off')
axs[1].add patch(plt.Rectangle((x, y), w, h,
linewidth=1, edgecolor='r', facecolor='none'))

# Hién thi khuon mât dâ cat


axs[2].imshow(cv2.cvtColor(face image,
cv2.COLOR_BGR2RGB)) axs[2].set
title(f'Khuén mât duoc cat')
axs[2].axis('off')

# Hien thi
hînh ành
plt.show()

Xoay ành

# output folder =
'/content/gdrive/MyDrive/nhanDienDT/opencv/AnhCh
anDung_rotate/'

# if not os.path.exists(output folder):


# os.makedirs(output_folder)
images =
os.listdir(image_folder)
for image_name in
images:
image path os.path.join(image folder, image
name)
# output_path =

os.path.join(output_folder, image_name)

img = cv2.imread(image_path)

# Xoay anh 45 dé
rotated 45 = imutils.rotate(img, 45)
rotated 45 pil

Image.fromarray(cv2.cvtColor(rotated_45,
cv2.COLOR BGR2RGB))
# rotated
45_pil.save(output_path.replace(".jpg", "
rotated_45.jpg"))

# Xoay anh -45 dé


rotated minus 45 = imutils.rotate(img, -45)
rotated minus 45_pil

Image.fromarray(cv2.cvtColor(rotated_minus_45,
cv2.COLOR BGR2RGB))
# rotated minus
45_pil.save(output_path.replace(".jpg", " rotated -
45.jpg"))

# Hien thi ành sau


khi xoay
plt.figure()
plt.imshow(rotated
45 pil)
plt.title("ành xoay trái
(45 dõ)") plt.show()

plt.figure()
plt.imshow(rotated minus 45
pil) plt.title("xoay phài
(-45 dõ)") plt.show()

Phu'o'ng pháp Canny phát hi/en edge

image_folder

'/content/gdrive/MyDrive/nhanDienDT/opencv/im

age/' images = os.listdir(image_folder)

for image name in images:


image_path os.path.join(image_folder,
image_name)

img = cv2.imread(image path)


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Ap dung Canny de tim canh


edges = cv2.Canny(gray, 300, 500)

# Chuyen doi thành hính ành


PIL edges_pil =
Image.fromarray(edges)

plt.figure()
plt.imshow(img,
cmap='gray')
plt.axis('off')
plt.show()

# Hien thi
ành canh
plt.figure()
plt.imshow(edges_pil,
cmap='gray')
plt.axis('off')
plt.show()

Xác d|nh các contour và vé bounding box


image_folder

'/content/gdrive/MyDrive/nhanDienDT/opencv/Bien

SoXe/' images = os.listdir(image_folder)

for image name in images:


image_path os.path.join(image_folder,
image_name)

img =
cv2.imread(image_pat
h) print(img.shape)
gray = cv2.cvtColor(img,
cv2.COLOR BGR2GRAY) thres =
cv2.adaptiveThreshold(gray, 255,
cv2.ADAPTIVE THRESH GAUSSIAN C, cv2.THRESH
BINARY_INV, 31, 10)

contours = cv2.findContours(thres,
cv2.RETR LIST, cv2.CHAIN APPROX
SIMPLE)
contours = imutils.grab contours(contours)
contours = sorted(contours, key=cv2.contourArea,
reverse=False)

# loop qua câc


contour number
0
for c in contours:
(x, y, w, h) =
cv2.boundingRect(c)
print(x, y, w, h)
if (40 < w < 90) and (100 < h < 180) and (h /
w > 1.5): cv2.rectangle(img, (x, y), (x +
w, y + h), (0, 255, 0), 2)
number += 1
crop = img[y:y + h, x:x + w]

cv2.imwrite("/content/gdrive/MyDrive/nhanDienDT/
opencv/.png".format(number
), crop)
print("Number of Contours found =
" + str(number)) # Hién thi ânh
Threshold
plt.figure()
plt.imshow(thres,
cmap='gray')
plt.axis('off')
plt.show()

# Hien thi ânh voi bounding


box plt.figure()
plt.imshow(cv2.cvtColor(img,
cv2.COLOR BGR2RGB)) plt.show()

You might also like