14.
Nhận diện biển báo
import cv2
import numpy as np
def empty(a):
pass
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale,
scale)
else:
imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0]
[0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
if len(imgArray[x][y].shape) == 2: imgArray[x][y]=
cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank]*rows
hor_con = [imageBlank]*rows
for x in range(0, rows):
hor[x] = np.hstack(imgArray[x])
ver = np.vstack(hor)
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
else:
imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1],
imgArray[0].shape[0]), None,scale, scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x],
cv2.COLOR_GRAY2BGR)
hor= np.hstack(imgArray)
ver = hor
return ver
def getContours(img):
contours,hierarchy =
cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
print(area)
if area>500:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt,True)
#print(peri)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)
print(len(approx))
objCor = len(approx)
x, y, w, h = cv2.boundingRect(approx)
path = 'bienso2.jpg'
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",78,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",116,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",0,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",21,255,empty)
cv2.createTrackbar("Val Min","TrackBars",231,255,empty)
cv2.createTrackbar("Val Max","TrackBars",253,255,empty)
while True:
img = cv2.imread(path)
imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
h_min = cv2.getTrackbarPos("Hue Min","TrackBars")
h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
print(h_min,h_max,s_min,s_max,v_min,v_max)
lower = np.array([h_min,s_min,v_min])
upper = np.array([h_max,s_max,v_max])
mask = cv2.inRange(imgHSV,lower,upper)
imgResult = cv2.bitwise_and(img,img,mask=mask)
imgContour = img.copy()
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgResult,(7,7),1)
imgCanny = cv2.Canny(imgBlur,50,50)
getContours(imgCanny)
imgBlank = np.zeros_like(img)
imgStack = stackImages(1,([img,imgGray,imgBlur],
[imgCanny,imgContour,imgBlank]))
cv2.imshow("Stack", imgStack)
cv2.waitKey(1)
Nhận xét :
buối 3: 1) tìm và vẽ histogram của ảnh xám bất kỳ. 2) cân bằng histogram đó và nhận xét so sánh vs
hàm có sẵn
clc
clear all
close all
warning off
x= imread('http://nghiencuuquocte.org/wp-content/uploads/2018/03/14.jpg');
subplot(3,2,1);
imshow(x);
title('Original Image');
subplot(3,2,2);
imhist(x);
title('Histogram of Original Image using built in function');
axis tight;
h=zeros(1,256);
[r c]=size(x);
totla_no_of_pixels=r*c;
n=0:255;
%%
j=histeq(x);
subplot(3,2,3);
imshow(j);
title('Histogram Equalization using built in function');
subplot(3,2,4);
imhist(j);
axis tight;
title('Histogram Equalization using built in function');
%%
%Calculating Histogram without built-in function
for i=1:r
for j=1:c
h(x(i,j)+1)=h(x(i,j)+1)+1;
end
end
%%
%Calculating Probability
for i=1:256
h(i)=h(i)/totla_no_of_pixels;
end
%%
%Calculating Cumulative Probability
temp=h(1);
for i=2:256
temp=temp+h(i);
h(i)=temp;
end
for i=1:r
for j=1:c
x(i,j)=round(h(x(i,j)+1)*255);
end
end
subplot(3,2,5);
imshow(x);
title('Histogram Equalized image using own code');
subplot(3,2,6);
imhist(x);
axis tight;
title('Histogram Equalization using own code');
Nhận xét :
Cột : tương ứng tần số suất hiện
Hàng : giá trị mức xám của ảnh
Khi sử dụng hàm có sẵn , giá trị các cột cao hơn so với lượt đồ gốc , số lượng các cột ít hơn và các điều
nhau , giá trị các cột gần bằng nhau và chênh nhau không nhiều .
Khi sử không sử dụng hàm có sẵn thì , hình dáng lượt đồ tương tự với lượt đồ gốc , ở bên phải số lượng
các cột mỏng hơn còn bên trái số lượng các cột nhiều hơn đứng xít nhau , giá trị các cột chênh nhau nhỏ
hơn so với lượt đồ gốc .
Buổi 6: Dùng phương pháp Alleyson để giải quyết bài toán demosaicing
img = imread('image\19.jpg');
[h, w, t] = size(img);
I = zeros(h,w);
I(1:2:h,1:2:w) = img(1:2:h,1:2:w,1);
I(1:2:h,2:2:w) = img(1:2:h,2:2:w,2);
I(2:2:h,1:2:w) = img(2:2:h,1:2:w,2);
I(2:2:h,2:2:w) = img(2:2:h,2:2:w,3);
FL = [-2 3 -6 3 -2;3 4 2 4 3;-6 2 48 2 -6;3 4 2 4 3;-2 3 -6 3 -2]/64;
lmn = conv2(I,FL,'same');
MC = I - lmn;
C = img;
mR = zeros(h,w);mG = zeros(h,w);mB = zeros(h,w);
mR(1:2:h,1:2:w) = 1;
mG(1:2:h,2:2:w) = 1;mG(2:2:h,1:2:w) = 1;
mB(2:2:h,2:2:w) = 1;
C1 = MC .* mR;
C2 = MC .* mG;
C3 = MC .* mB;
WRB = [1 2 1;2 4 2;1 2 1] / 4;
WG = [0 1 0; 1 4 1; 0 1 0] / 4;
res = img;
res(:,:,1) = conv2(C1,WRB,'same') + lmn;
res(:,:,2) = conv2(C2, WG,'same') + lmn;
res(:,:,3) = conv2(C3, WRB,'same') + lmn;
imshow(res,[])
(ảnh sau khôi phục) (ảnh gốc)
buối 4
----------------bài 1-------------------------
% Load the input image
img = imread('45.JPG');
% Convert the image to grayscale
gray_img = rgb2gray(img);
% Define the three different kernels
kernel1 = ones(3,3) / 9;
kernel2 = ones(5,5) / 25;
kernel3 = ones(9,9) / 81;
% Apply each kernel using the "imfilter" function
result1 = imfilter(gray_img, kernel1, 'symmetric', 'same');
result2 = imfilter(gray_img, kernel2, 'symmetric', 'same');
result3 = imfilter(gray_img, kernel3, 'symmetric', 'same');
% Display the original and filtered images using subplot
figure;
subplot(2,2,1)
imshow(gray_img);
title('Original Image');
subplot(2,2,2)
imshow(result1);
title('3x3 Mean Filtered Image');
subplot(2,2,3)
imshow(result2);
title('5x5 Mean Filtered Image');
subplot(2,2,4)
imshow(result3);
title('9x9 Mean Filtered Image');
----------------------bài 2---------------------------------------------------
img = rgb2gray(imread('45.jpg'));
[h, w] = size(img);
img = double(img) + 20 * randn(h,w);
subplot(2,2,1)
imshow(img,[])
kernel1 = ones(3,3) / 9;
kernel2 = ones(5,5) / 25;
kernel3 = ones(9,9) / 81;
I1 = imfilter(img, kernel1,'same');
[h1, w1] = size(I1)
I2 = imfilter(img, kernel2,'same');
I3 = imfilter(img, kernel3,'same');
subplot(2,2,2)
imshow(I1,[]);
subplot(2,2,3)
imshow(I2,[]);
subplot(2,2,4)
imshow(I3,[]);
-------------------------bài 3----------------------------
img = rgb2gray(imread('45.jpg'));
[h, w] = size(img)
H1 = [1 ;2 ;1] / 4;
H2 = transpose(H1);
% Cau A
Y1 = imfilter(img, H1,'same');
Y2 = conv2(img, H2,'same');
subplot(2,2,1);
imshow(Y1,[]);
title('Y1');
subplot(2,2,2);
imshow(Y2,[]);
title('Y2');
% Cau B
H = [1 2 1; 2 4 2; 1 2 1] / 16;
Y3 = conv2(img, H, 'same');
size(Y3);
subplot(2,2,3);
imshow(Y3,[]);
title('Y3');
subplot(2,2,4);
imshow(img,[]);
title('Original');
max(abs(Y2-Y1));
max(abs(Y3-Y2));
Nhận xét
Bài 5
img = imread('peppers.png');
% Extract color channels
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
% Set every other row and column to zero in the red channel
R(2:2:end,:) = 0;
R(:,2:2:end) = 0;
% Set every other pixel to zero in the green channel
G(1:2:end,2:2:end) = 0;
G(2:2:end,1:2:end) = 0;
% Set every other row and column to zero in the blue channel
B(2:2:end,:) = 0;
B(:,2:2:end) = 0;
% Combine color channels into a new image
I = cat(3, R, G, B);
% Display the new image
figure;
imshow(I);
% Apply a weighted filter to each color channel separately
WRB = [1 2 1; 2 4 2; 1 2 1] / 4;
WG = [0 1 0; 1 4 1; 0 1 0] / 4;
R = conv2(R, WRB, 'same');
G = conv2(G, WG, 'same');
B = conv2(B, WRB, 'same');
% Combine color channels into a new image
I = cat(3, R, G, B);
% Display the new image
figure;
imshow(I);
Buổi 7, 8, 9, 10: không có
buổi 1: 1) viết chương trình xoay ảnh một góc alpha
% Đọc ảnh
img = imread('peppers.png');
% Xoay ảnh một góc 45 độ
alpha = 45;
rotated_img = imrotate(img, alpha);
% Hiển thị ảnh gốc và ảnh sau khi xoay
subplot(1, 2, 1);
imshow(img);
title('Ảnh gốc');
subplot(1, 2, 2);
imshow(rotated_img);
title(['Ảnh sau khi xoay ', num2str(alpha), ' độ']);
buối 2: chia 1 ảnh thành 16 phần rồi xáo trộn
% Xáo trộn các phần của ảnh
idx = randperm(num_rows * num_cols);
C_shuffle = C(idx);
% Tạo ảnh mới từ các phần đã xáo trộn
img_new = cell2mat(reshape(C_shuffle, [num_rows, num_cols]));
% Hiển thị ảnh gốc và ảnh mới
figure;
subplot(1, 2, 1);
imshow(img);
title('Ảnh gốc');
subplot(1, 2, 2);
imshow(img_new);
title('Ảnh sau khi xáo trộn');
buổi 13
-----------------------------------------
% Tạo dữ liệu mẫu
rng(1); % Thiết lập seed để dữ liệu được tạo ngẫu nhiên có thể tái sử dụng
X = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
% Hiển thị dữ liệu mẫu
figure;
scatter(X(:,1),X(:,2),10,'black');
title('Dữ liệu mẫu');
% Sử dụng K-Means để phân loại dữ liệu vào 2 cụm
num_clusters = 2;
[idx, C] = kmeans_code(X, num_clusters);
% Hiển thị kết quả phân loại
figure;
scatter(X(idx==1,1),X(idx==1,2),10,'red');
hold on;
scatter(X(idx==2,1),X(idx==2,2),10,'blue');
scatter(C(:,1),C(:,2),50,'black','filled');
title('Phân loại dữ liệu sử dụng K-Means');
legend('Cụm 1','Cụm 2','Tâm cụm');
function [idx, C] = myKMeans(X, k)
% MYKMEANS - Phân cụm tập dữ liệu X thành k cụm bằng thuật toán K-Means
% INPUTS:
% X: ma trận dữ liệu kích thước m x n, trong đó m là số mẫu, n là số đặc trưng.
% k: số lượng cụm mong muốn
% OUTPUTS:
% idx: vector kích thước m x 1, chứa chỉ số của các cụm tương ứng với mỗi mẫu trong
X.
% C: ma trận k x n, chứa các centroid tương ứng với các cụm.
% Khởi tạo ngẫu nhiên các centroid
[m, n] = size(X);
idx = randi(k, m, 1);
C = zeros(k, n);
for i = 1:k
C(i,:) = mean(X(idx==i,:));
end
% Thực hiện thuật toán K-Means
maxIter = 100; % Số lần lặp tối đa
for iter = 1:maxIter
% Gán các mẫu vào các cụm tương ứng
D = pdist2(X, C);
[~, idx] = min(D, [], 2);
% Cập nhật các centroid
for i = 1:k
C(i,:) = mean(X(idx==i,:));
end
end
end
Buổi 11: < ảnh >