오늘보다 더 나은 내일의 나에게_

비전공자의 IoT 국비 교육 수강일지 Day_93 본문

비전공자의 코딩일지

비전공자의 IoT 국비 교육 수강일지 Day_93

chan_96 2022. 4. 29. 16:27
728x90

머신러닝

📌리눅스 명령어 정리

# 현재 작업 디렉토리 확인
!pwd

# 현재 작업 디렉토리의 폴더 내용 확인
!ls

# 폴더 이동
%cd 

# 폴더 생성 
mkdir


# 파일/폴더 복사 
cp


# 파일/폴더 이동 
mv


# 파일/폴더 삭제 
rm


# 추가 도구 설치 
apt-get

마스크 착용여부 판단 모델(이진분류)

훈련데이터와 평가데이터로 나누기(사진파일형태 유지)
import os
import numpy as np

file_names_with_mask = os.listdir('./data/with_mask')
file_names_without_mask = os.listdir('./data/without_mask')

# 난수 추출 기능
np.random.choice([10,5,99,100], size=2, replace=False) # replace=False -> 비복원 추출

np.random.seed(429)
test_with_mask = np.random.choice(file_names_with_mask,
                                  size=int(len(file_names_with_mask)*0.2),
                                  replace=False)
print(len(test_with_mask))
print(test_with_mask[:10])

np.random.seed(429)
test_without_mask = np.random.choice(file_names_without_mask,
                                  size=int(len(file_names_without_mask)*0.2),
                                  replace=False)

# 폴더 생성 및 파일 복사
!mkdir ./data/train
!mkdir ./data/test
!cp -r ./data/with_mask ./data/train/with_mask
!cp -r ./data/without_mask ./data/train/without_mask
!mkdir ./data/test/with_mask
!mkdir ./data/test/without_mask

# 사진 이동
for name in test_with_mask :
  !mv ./data/train/with_mask/$name ./data/test/with_mask/
 
# 사진 이동
for name in test_without_mask :
!mv ./data/train/without_mask/$name ./data/test/without_mask/

 


✨모델링
- 전이학습 모델 : MobileNetV3

- 사진폴더부터 모델학습까지 한번에 이어지는 파이프라인을구축(tensorflow의 기능 활용)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D
from tensorflow.keras.applications import MobileNetV3Large
from tensorflow.keras.applications.mobilenet_v3 import preprocess_input # 사전학습모델용 전처리함수
from tensorflow.keras.preprocessing.image import ImageDataGenerator #이미지 증식

pre_trained_model = MobileNetV3Large(include_top=False,
                                     weights='imagenet',
                                     input_shape=(224,224,3))
pre_trained_model.trainable = False

mask_gen_train = ImageDataGenerator(rotation_range=20,
                                    zoom_range=0.15,
                                    width_shift_range=0.2,
                                    height_shift_range=0.2,
                                    shear_range=0.15,
                                    horizontal_flip=True,
                                    preprocessing_function=preprocess_input)
                                    
mask_get_test = ImageDataGenerator(preprocessing_function=preprocess_input)

mask_model = Sequential() # 뼈대 생성
mask_model.add(pre_trained_model) # 사전학습모델(MobileNetV3)
mask_model.add(GlobalAveragePooling2D())
mask_model.add(Flatten()) # 추출된 특징을 1차원으로 만들어주는 레이어
mask_model.add(Dense(units=128,activation='relu')) # 중간층
mask_model.add(Dense(units=1,activation='sigmoid')) # 출력층

mask_model.compile(loss="binary_crossentropy",
                   optimizer='Adam',
                   metrics=['accuracy'])

mask_model.fit(mask_gen_train.flow_from_directory("./data/train",class_mode='binary'),
               epochs=10)

mask_model.evaluate(mask_get_test.flow_from_directory("./data/test", class_mode='binary'))

mask_model.save('./mask_detect_model.h5')


✨영상에서 마스크 착용 여부 판별하기

import cv2

# 얼굴검출 모델 사용하기
face_model = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")

#반복문 이용해서 영상 출력하기
try : 
    print("영상로딩을 시작합니다..")
    video_cap = cv2.VideoCapture("./movie4.mp4")
    #video_cap = cv2.VideoCapture(0) 0으로 작성시 컴퓨터와 연결된 카메라 연동
    
    while True:
        ret,frame = video_cap.read()
        
        if ret :
            # 얼굴검출 코드 추가
            faces = face_model.detectMultiScale(frame, 1.2,10)
            for(x,y,w,h) in faces:
                cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
            
            cv2.imshow("video",frame)
            k = cv2.waitKey(25) # 초당 프레임수를 맞추기 위함 : 1000/24
        else:
            break;
            
        if k == 27 : #27번은 ESC
            break;
            
    cv2.destroyAllWindows()
    video_cap.release()
except :
    print("영상로딩 실패")​

안드로이드

두더지 잡기 게임 실습


코드

더보기
MoreActivity
package com.example.ex0428;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

public class MoreActivity extends AppCompatActivity {

    TextView tvTime, tvCount;
    ImageView[] moreArr = new ImageView[9];
    boolean isPlaying = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);

        //타이머 스레드 생성
        MoreTimerThread t_thread  = new MoreTimerThread();
        t_thread.start();

        tvTime = findViewById(R.id.tvTime);
        tvCount = findViewById(R.id.tvCount);

        //동적으로 리소스ID접근 후 ImageView 초기화
        for(int i=0;i< moreArr.length;i++){
            final int pos = i;

            //img1 ~ img9까지의 리소스ID 접근
            int resId = getResources().getIdentifier("img"+(i+1),"id",getPackageName());
            moreArr[i] = findViewById(resId);

            //imageView에 tag설정
            //tag: View에 대한 상태값 저장
            moreArr[i].setTag("down");

            MoreMoveThread thread = new MoreMoveThread(i);
            thread.start();

            //두더지(ImageView)를 클릭했을 때
            moreArr[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    String status = moreArr[pos].getTag().toString();

                    //두더지의 상태체크 -> 잡은개수를 업데이트(증/감)
                    //잡은개수에 대한 카운트 기능을 구현하시오.
                    int count = Integer.parseInt(tvCount.getText().toString());

                    if(status.equals("up")){
                        count += 1;
                    }else{
                        if(count > 0){
                            count -= 1;
                        }
                    }
                    tvCount.setText(String.valueOf(count));
                }
            });
        }//end for
    }//end onCreate

    class MoreMoveThread extends Thread{

        MoreMoveHandler handler = new MoreMoveHandler();

        int more_pos;

        public MoreMoveThread(int more_pos){
            this.more_pos = more_pos;
        }

        @Override
        public void run() {

            Random random = new Random();
            //두더지가 위/아래 머물러 있는 시간을 랜덤으로 생성하시오.
            while(isPlaying) {
                int downTime = random.nextInt(1500)+500;
                int upTime = random.nextInt(1500)+500;

                //아래 머물러 있는 시간
                try {
                    Thread.sleep(upTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //저장해야 할 데이터: 두더지 번호, 변경할 두더지 이미지, 두더지 상태
                Message msg = new Message();
                msg.arg1 = more_pos;
                msg.arg2 = R.drawable.up;
                msg.obj = "up";

                handler.sendMessage(msg);

                try {
                    Thread.sleep(downTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                msg = new Message();
                msg.arg1 = more_pos;
                msg.arg2 = R.drawable.down;
                msg.obj = "down";

                handler.sendMessage(msg);
            }
        }
    }//end MoreMoveThread class

    class MoreMoveHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {

            int pos = msg.arg1;
            int img = msg.arg2;
            String status = (String) msg.obj;

            moreArr[pos].setImageResource(img);
            moreArr[pos].setTag(status); //up down 상태값 저장

        }
    }//end MoreMoveHandler class

    class MoreTimerThread extends Thread{

        MoreTimerHandler handler = new MoreTimerHandler();

        @Override
        public void run() {

            for(int i = 30;i > -1;i--){
                Message msg = new Message();
                msg.arg1 = i;

                handler.sendMessage(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }//end for
        }// end run()
    }//end MoreTimerThread class

    class MoreTimerHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            int time = msg.arg1;
            tvTime.setText(String.valueOf(time));

            //0초가 되었을 때 두더지 움직임 정지
            if(time == 0){
                isPlaying = false;
            }
        }
    }//end MoreTimerHandler class
}
728x90
Comments