https://github.com/mk-minchul/AdaFace.git
GitHub - mk-minchul/AdaFace
Contribute to mk-minchul/AdaFace development by creating an account on GitHub.
github.com
paper : https://arxiv.org/abs/2204.00964
AdaFace: Quality Adaptive Margin for Face Recognition
Recognition in low quality face datasets is challenging because facial attributes are obscured and degraded. Advances in margin-based loss functions have resulted in enhanced discriminability of faces in the embedding space. Further, previous studies have
arxiv.org
face recognition 모델 Adaface 실행 과정 및 결과 포스팅이 잘 안보여서 직접 작성
RTX 4060 Ti 기준
1. 환경구성
아나콘다에서 가상환경 adaface 생성 후에 진행
깃헙에서 제공하는 환경은 다음과 같다
conda create --name adaface pytorch==1.8.0 torchvision==0.9.0 cudatoolkit=10.2 -c pytorch
conda activate adaface
conda install scikit-image matplotlib pandas scikit-learn
pip install -r requirements.txt
pip install -r requirements.txt에서 위와 같은 패키지 버전 호환 오류 계속 발생
이후 수정한 버전의 conda list 및 cuda 버전 포함 txt 파일 첨부
오류 발생하시는 분은 참고
2. Pretrained 된 모델 선택
아키텍쳐만 R50, R100으로 변경해서 WebFace4M과 MS1MV2 데이터셋을 학습시킨 모델로 선택함
모델 선택은 자유,,,
3. Test 해보기
전처리로는 얼굴랜드마크를 이용한 정렬(alignment)이 들어가고 그 이후에 MTCNN(Multi-task Cascaded Convolutional Networks)를 사용하여 이미지 유사도를 판별하는듯 하다.
alignment 이후에는 112x112x3 crop 으로 BGR 이미지로 전처리 되어 모델에 입력된다. 만약 alignment 과정을 생략하고 싶다면 직접 112x112x3 crop 으로 BGR 로 전처리된 이미지를 모델에 먹이면 된다 냠.
이제 이미 포함되어 있는 test images로 test를 해보자.
face_alignment/test_images 폴더 안에는 아래와 같은 3개의 이미지가 들어있는 것을 확인해 볼 수 있다.
로버트 다우니 주니어 2장과 니콜라스 케이지의 사진 1장이 들어있다. 코드를 실행시켜보자
python inference.py
tensor([[ 1.0000, 0.7334, -0.0655],
[ 0.7334, 1.0000, -0.0277],
[-0.0655, -0.0277, 1.0000]], grad_fn=<MmBackward0>)
문제없이 실행되었다면 결과는 위와 같다. 숫자가 1에 가까울수록 동일인으로 인식되었다는 의미이다
왼쪽 위부터 순서대로 img1과 img1은 같은 로버트 다우니 주니어 사진이므로 1.0000이 뜨고, im1과 img2는 동일인물이지만 이미지가 다르기 때문에 1.0000보다는 낮은 0.7334가 뜬다 img1과 img3은 아예 다른 인물이기 때문에 - 혹은 0에 가까운 수치가 뜬다. 다음줄도 마찬가지이다.
#직접 테스트 해보기 위해서 inference.py를 살펴보자
import net
import torch
import os
from face_alignment import align
import numpy as np
adaface_models = {
'ir_50':"pretrained/adaface_ir50_ms1mv2.ckpt", #아키텍처와 훈련된 모델을 변경할수 있다
}
def load_pretrained_model(architecture='ir_50'):
# load model and pretrained statedict
assert architecture in adaface_models.keys()
model = net.build_model(architecture)
statedict = torch.load(adaface_models[architecture])['state_dict']
model_statedict = {key[6:]:val for key, val in statedict.items() if key.startswith('model.')}
model.load_state_dict(model_statedict)
model.eval()
return model
def to_input(pil_rgb_image): #전처리 과정
np_img = np.array(pil_rgb_image)
brg_img = ((np_img[:,:,::-1] / 255.) - 0.5) / 0.5
tensor = torch.tensor([brg_img.transpose(2,0,1)]).float()
return tensor
if __name__ == '__main__':
model = load_pretrained_model('ir_50')
feature, norm = model(torch.randn(2,3,112,112))
test_image_path = 'face_alignment/test_images' #이 경로에 직접 사진을 넣는다
features = []
for fname in sorted(os.listdir(test_image_path)):
path = os.path.join(test_image_path, fname)
aligned_rgb_img = align.get_aligned_face(path)
bgr_tensor_input = to_input(aligned_rgb_img)
feature, _ = model(bgr_tensor_input)
features.append(feature)
similarity_scores = torch.cat(features) @ torch.cat(features).T
print(similarity_scores) #이미지간의 유사도를 출력한다
이 상태로 끝내도 좋지만 비교대상의 두 이미지 파일의 이름과 similarity score, confidence 를 json 파일에 저장하고 그걸 csv로 변환하려면 추가적인 코드 작성이 필요하다.
근데 올리기 귀찮다 ㅈㅅ 나중에 수정하겟슴
오류 발생 질문 및 관련 사항 수정 대환영임니다
'코드' 카테고리의 다른 글
[matlab] Andrea Fusiello, Rectification of Stereo Images 스테레오 이미지 정류 알고리즘 (0) | 2023.04.04 |
---|---|
[matlab] 이미지 리사이즈 코드 (0) | 2023.03.20 |
[python] 이미지 증강 코드 data augmentaion (0) | 2023.03.20 |
[python] Fashion mnist mlp (0) | 2023.02.24 |
[python] 말과 사람 구분하기 horse or human (0) | 2023.02.24 |