Skip to content

Commit

Permalink
Merge branch 'develop' into ljy67122
Browse files Browse the repository at this point in the history
  • Loading branch information
sycuuui committed May 2, 2024
2 parents 18fdd60 + 9b8ba21 commit b8c4dcc
Show file tree
Hide file tree
Showing 28 changed files with 203,594 additions and 1 deletion.
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ wider face.v3i.yolov5pytorch
dist
build
myenv
svm/**
1 change: 1 addition & 0 deletions .idea/.name

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions .idea/flask.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified __pycache__/app.cpython-311.pyc
Binary file not shown.
Binary file modified pytorch/__pycache__/mosaic_jiyeon.cpython-311.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion pytorch/mosaic_jiyeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
def mosaic(video_path, image_paths):
# YOLOv5 모델 로드
# model = torch.hub.load('./pytorch/yolov5', 'custom', path='./pytorch/best.pt', source='local')
model = torch.hub.load('ultralytics/yolov5', 'custom', path='./pytorch/best.pt')
model = torch.hub.load('ultralytics/yolov5', 'custom', path='./pytorch/best.pt',source='local')
output_video_path = os.path.join('tmp', video_path)
# 특정 사람의 얼굴 이미지 로드
# person_image = face_recognition.load_image_file("goognyoo.png")
Expand Down
Binary file added svm/Gongyoo/image1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/image2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/image3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/image4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/image5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added svm/Gongyoo/img_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
82 changes: 82 additions & 0 deletions svm/cnn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import os
import cv2
import numpy as np
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical

# 이미지 로딩 및 전처리 함수
def load_images_from_directory(directory, size=(64, 64)):
images = []
for filename in os.listdir(directory):
img_path = os.path.join(directory, filename)
if filename.endswith(".jpg") or filename.endswith(".png"):
img = cv2.imread(img_path)
if img is None:
print(f"Warning: Image not loaded properly from {img_path}")
continue
img = cv2.resize(img, size)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
images.append(img)

# Convert the list of images to a 4D numpy array
images = np.array(images) # This should create an array of shape (num_images, 64, 64, 3)
return images

# 데이터셋 로드
# celeba_images = load_images_from_directory('img_align_celeba')
images = load_images_from_directory('output')

print("Data Loaded Successfully")
# print(f"Number of CelebA images: {len(celeba_images)}")
print(f"Number of Output images: {len(images)}")

# 데이터 결합 및 분할
all_images = np.concatenate(( images), axis=0)
X_train, X_test = train_test_split(images, test_size=0.2, random_state=42)

data_generator = ImageDataGenerator(rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True)
train_generator = data_generator.flow(X_train, batch_size=32)



print("Data split into training and test sets.")
print(f"Training set size: {len(X_train)}")
print(f"Test set size: {len(X_test)}")

# 모델 구축 함수
def build_model(input_shape):
model = Sequential([
Input(shape=input_shape),
Conv2D(32, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(2, activation='softmax') # Assuming binary classification for simplicity
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model

model = build_model((64, 64, 3))

# 데이터 증강
data_generator = ImageDataGenerator(rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True)
train_generator = data_generator.flow(X_train, batch_size=32)

# 모델 학습 (임시로 labels 만들기 - 실제 사용 시 적절한 labels 준비 필요)
dummy_labels = np.random.randint(2, size=len(X_train))
dummy_labels = to_categorical(dummy_labels, num_classes=2)
# Assuming you have a 'model' defined
model.fit(train_generator, epochs=10, validation_data=(X_test, np.random.randint(0, 2, size=(len(X_test), 1))))
print("Model training complete.")

# 모델 저장
model.save('face_recognition_model.h5')
print("Model saved successfully.")
68 changes: 68 additions & 0 deletions svm/cnn2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import cv2
import numpy as np
from skimage.feature import hog
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn import svm
from sklearn.metrics import classification_report, confusion_matrix
import joblib
import os

# 특징 추출 함수
def extract_hog_features(image_path):
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"Failed to load image: {image_path}")
return None
resized_img = cv2.resize(image, (64, 64))
fd = hog(resized_img, orientations=8, pixels_per_cell=(16, 16),
cells_per_block=(1, 1), visualize=False, feature_vector=True)
return fd

def load_images_from_directory(directory, sample_size=None):
features = []
labels = []
image_files = [os.path.join(directory, file) for file in os.listdir(directory) if file.endswith('.jpg')]
if sample_size:
image_files = np.random.choice(image_files, size=sample_size, replace=False)

total_images = len(image_files)
for index, file in enumerate(image_files):
feat = extract_hog_features(file)
if feat is not None:
features.append(feat)
labels.append(1) # 모든 이미지에 대해 '얼굴' 레이블(1) 부여
print(f"Processed {index + 1}/{total_images} images.")

return features, labels

# 데이터셋 경로 설정
celeba_dir = './img_align_celeba' # CelebA 이미지 디렉토리
wider_face_dir = './output' # WIDER FACE 이미지 디렉토리

# Load data
celeba_features, celeba_labels = load_images_from_directory(celeba_dir, sample_size=500)
wider_features, wider_labels = load_images_from_directory(wider_face_dir, sample_size=500)

# 데이터 합치기
features = np.vstack((celeba_features, wider_features))
labels = np.hstack((celeba_labels + wider_labels))
print('데이터 합치기 끝')

# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.25, random_state=42)
print('데이터 분할 끝')

# 그리드 서치를 이용한 SVM 튜닝 및 훈련
parameters = {'C': [0.1, 1, 10, 100], 'gamma': [1, 0.1, 0.01, 0.001], 'kernel': ['rbf', 'linear']}
grid_search = GridSearchCV(svm.SVC(), parameters, refit=True, verbose=2, cv=3)
grid_search.fit(X_train, y_train)
print('튜닝 및 훈련 끝')

# 모델 평가
y_pred = grid_search.predict(X_test)
print("Best parameters found:", grid_search.best_params_)
print("Classification Report:\n", classification_report(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))

# 모델 저장
joblib.dump(grid_search.best_estimator_, 'svm_face_recognition2.pkl')
Binary file added svm/cutVideo.mp4
Binary file not shown.
Loading

0 comments on commit b8c4dcc

Please sign in to comment.