[CAM]Image Download

CAM
Author

SEOYEON CHOI

Published

September 14, 2023

https://seoyeonc.github.io/chch/cnn/feature%20extraction/big%20data%20analysis/2022/01/11/bd_9주차.html

https://seoyeonc.github.io/chch/cam/2022/01/10/bd-8주차_1.html

import

import torch 
from fastai.vision.all import *
import cv2
import numpy as np
import os
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageFile
from PIL import Image
ImageFile.LOAD_TRUNCATED_IMAGES = True
from torchvision.utils import save_image
import os
import rpy2
import rpy2.robjects as ro 
from rpy2.robjects.vectors import FloatVector 
from rpy2.robjects.packages import importr
def label_func(f):
    if f[0].isupper():
        return 'cat' 
    else: 
        return 'dog' 

Original Image로 학습하는 과정

path=untar_data(URLs.PETS)/'images'
# path.ls()
files=get_image_files(path)
dls=ImageDataLoaders.from_name_func(path,files,label_func,item_tfms=Resize(512)) 
lrnr=cnn_learner(dls,resnet34,metrics=error_rate)
lrnr.fine_tune(1)
net1=lrnr.model[0]
net2=lrnr.model[1] 
net2 = torch.nn.Sequential(
    torch.nn.AdaptiveAvgPool2d(output_size=1), 
    torch.nn.Flatten(),
    torch.nn.Linear(512,out_features=2,bias=False))
net=torch.nn.Sequential(net1,net2)
lrnr2=Learner(dls,net,metrics=accuracy) 
lrnr2.fine_tune(10) 
interp = ClassificationInterpretation.from_learner(lrnr2)
interp.plot_confusion_matrix()
interp.print_classification_report()

랜덤박스가 들어간 개 고양이 그림 다운로드

path=untar_data(URLs.PETS)/'images'
if str(list(path.ls())[103]).split('/')[-1].split('.')[-1]=="jpg" :
    print("jpg")
#name=str(list(path.ls())[i]).split('/')[-1]
path.ls()
for i in range(7393) :
    img = PILImage.create(get_image_files(path)[i])
    img = img.resize([512,512], resample=None, box=None, reducing_gap=None)
    name = str(list(path.ls())[i]).split('/')[-1]
    fname = name.split('.')[-1]
    if fname!="jpg" : 
        print(name)
    else : pass

.mat 파일 같은 이상한 거 삭제

# os.remove(r"/home/csy/.fastai/data/oxford-iiit-pet/images/Abyssinian_100.mat")
# os.remove(r"/home/csy/.fastai/data/oxford-iiit-pet/images/Abyssinian_102.mat")
# os.remove(r"/home/csy/.fastai/data/oxford-iiit-pet/images/Abyssinian_101.mat")
# os.mkdir("random_pet_one")
# for i in range(len(path.ls())) :
#     img = PILImage.create(get_image_files(path)[i])
#     img = img.resize([512,512], resample=None, box=None, reducing_gap=None)
#     (w, h) = (img.shape[0], img.shape[1])
#     a = random.uniform(0, w*0.7)
#     b = random.uniform(0, h*0.9)
#     shape = [(a, b), (a+85, b+85)]
#     font = ImageFont.truetype("DejaVuSans.ttf", round(h*0.075))
#     name = str(list(path.ls())[i]).split('/')[-1]
#     fname = name.split('.')[-1]
#     if name[0].isupper() == True :
#         img1 = ImageDraw.Draw(img)  
#         img1.rectangle(shape, fill ="white", outline ="black")
#         ImageDraw.Draw(img).text((a+5, b+15), 'Cat', (0,0,0), font=font)
#         img.save("random_pet_one/"+name)
#     else: 
#         img1 = ImageDraw.Draw(img)  
#         img1.rectangle(shape, fill ="black", outline ="black")
#         ImageDraw.Draw(img).text((a+5, b+15), 'Dog', (255,255,255), font=font)
#         img.save("random_pet_one/"+name)