First step/AI 기초반

[TIL]21.07.21openCV 기초

Joshua21 2021. 7. 21. 21:38

오늘은 몸상태가 너무 않좋아서 수업을듣기가정말 힘들었다.

거짓말 안보태고 30분마다 한번씩 토를 했다. 라이브 수업듣다가  화면끄고 튀어가서 토하고 다시코드짜고하면서 겨우겨우 들었다.

 

 먼저 지난시간에 했었던 소캣 실습을복습했다.

 

import socket
from _thread import*
from pynput import keyboard
import time
import threading
import sys

bServerLoopEnd=False
bClientWaitEnd=False

def Mainloop():
    if(bServerLoopEnd==False): 
        threading.Timer(0.1,Mainloop).start()
    else:
        print('server close')
        server_socket.clsoe()
        sys.exit()
        
def on_press(key):
    '''
    try:
        print('Alophanumeric key pressed: {0}'.format(kye.char))
        
    except AttributeError:
        print('special key pressed: {0}'.format(key))
    '''
def on_release(key):
    global bClientWaitLoopEnd #전역 변수 bLoopEnd 사용 
    if  key == keyboard.key.esc:
        print("=====esc=====")
        bLoopEnd=True
        return False
#쓰레드에서 실행되는 코드
def clientchkThreaded(i):
    global bServerLoopEnd
    global bClientWaitEnd
    while True:
        print('clientChkThreaded wait!!')
        
        server_socket,settimeout(1)
        if (bClientWaitEnd == False):
            try:
                client_socket, addr=server_socket.accept()
            except socket.timeout:
                continue
            server_soket.settimeout(None)
            print('client_socket connected!!',addr)
            threaded(client_socket,addr)
        else:
            print('keyboardInterrupt')
            bServerLoopEnd = True
            break
            
            
            
            
def threaded(client_socket,addr):
    print('connected by : ',addr[0],':',addr[1])
    while True:
        try:
            #데이터가 수신되면 클라이언트에 다시 전송합니다.(에코)
            data=client_socket.recv(1024)
            
            if not data:
                print('Disconnected by '+ addr[0],':',addr[1])
                break
            print('Received from'+addr[0],':',addr[1],data.decode())
            
            client_socket.send(data)
            
        except ConnectionResetError as e:
            print('Disconnected by'+addr[0],':',addr[1])
            break
    
    print('end')
    client_socket.close()
    
    
HOST ='127.0.0.1'
PORT=9999
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
server_socket.bind((HOST,PORT))
server_socket.listen()

print('server start')

i=0
start_now_thread(ClientChkThreaded,(i,))
MainLoop()

#keayboaerd listner를 등록 colletc events until released
with keyboard.Listener(on_press=on_press,on_release=on_release)as listener:
    lintener.join()
    
#리스너 등록방법2    
# listener=keyboard.Listener(on_press=on_press,on_release=on_release)
# listener.start()
# listener.join

 

open cv를 배우기 시작했다.

import cv2
import numpy as np

image= np.zeros((300,400), np.uint8)
image.fill(200)

cv2.imshow('Window title',image)

key= cv2.waitKey(0)
print('key :',key)
cv2.destroyAllWindows()

 

import cv2
import numpy as np

image= np.zeros((200,400), np.uint8)
image[:]=200

title1,title2='Position1','Position2'
cv2.namedWindow(title1,cv2.WINDOW_AUTOSIZE)
cv2.namedWindow(title2)
cv2.moveWindow(title1,150,150)
cv2.moveWindow(title2,400,50)

cv2.imshow(title1,image)
cv2.imshow(title2,image)
cv2.waitKey(0)
cv2.destroyAllWIndows()

 

import cv2
import numpy as np

image= np.zeros((200,300), np.uint8)
image.fill(255)
image[:100] = 100
title1,title2='Autosize','normal'
cv2.namedWindow(title1,cv2.WINDOW_AUTOSIZE)
cv2.namedWindow(title2,cv2.WINDOW_NORMAL)

cv2.imshow(title1,image)
cv2.imshow(title2,image)
cv2.resizeWindow(title1,400,300)
cv2.resizeWindow(title2,400,300)

cv2.waitKey(0)
cv2.destroyAllWindows()

 

import cv2
import numpy as np

switch_case={
    ord('a'):'a키입력',
    ord('b'):'b키입력',
    0x41: 'A키 입력',
    int('0x42',16): 'b키 입력',
    2424832:'왼쪽 화살표키 입력',
    2490368:'위쪽 화살표키 입력',
    2555904:'오른쪽 화살표키 입력',
    2621440:'아래쪽 화살표키 입력'
}

image=np.ones((200,300),np.uint8)
cv2.namedWindow('keyboaerd Event')
cv2.imshow('keyboard Event',image)
while True:
    key = cv2.waitKeyEx(100)
    if key==27: #esc누르면 종료
        break
    try:
        result= switch_case[key]
        print(result)
    except KeyError:
        result=-1
cv2.destroyAllWindows()

 

import cv2
import numpy as np

def onMouse(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print('마우스 왼쪽 버튼 누르기')
    elif event == cv2.EVENT_RBUTTONDOWN:
        print('마우스 오른쪽 버튼 누르기')
    elif event== cv2.EVENT_RBUTTONUP:
        print('마우스 오른쪽 버튼 때기')
    elif event== cv2.EVENT_LBUTTONUP:
        print('마우스 왼쪽 버튼 때기')

image=np.full((200,300),255,np.uint8)

title1,title2 = 'Mouse Event1','Mouse Event2'
cv2.imshow(title1,image)
cv2.imshow(title2,image)

cv2.setMouseCallback('Mouse Event1',onMouse)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

import cv2
import numpy as np

def onChange(value):
    global image
    print('value 값 : ', value)
    image=np.zeros((300,500),np.uint8)
    image=image + value
    cv2.imshow(title,image)
    
image=np.zeros((300,500),np.uint8)

title='Trackbar Event'
cv2.imshow(title,image)

cv2.createTrackbar('Brightness',title,image[0][0],255,onChange)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#왼,오마우스버튼으로 화면밝기를10씩조정
import cv2
import numpy as np

def onChange(value):
    global image,title
    image=np.zeros((300,500),np.uint8)
    image=image + value
    cv2.imshow(title,image)
    
def onMouse(event,x,y,flags,param):
    global image,bar_name
    if event == cv2.EVENT_RBUTTONDOWN:
        if (image[0][0]<246): image=image+10
        cv2.setTrackbarPos(bar_name,title,image[0][0])
        cv2.imshow(title,image)
        
    elif event == cv2.EVENT_LBUTTONDOWN:
        if (image[0][0]>=10): image=image-10
        cv2.setTrackbarPos(bar_name,title,image[0][0])
        cv2.imshow(title,image)
    
image=np.zeros((300,500),np.uint8)

title='Trackbar &Mouse Event'
bar_name='Brightness'
cv2.imshow(title,image)

cv2.createTrackbar(bar_name,title,image[0][0],255,onChange)
cv2.setMouseCallback(title,onMouse)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#왼,오버튼트로 화면 흑,백으로 바꾸기
import cv2
import numpy as np

def onChange(value):
    global image,title
    image=np.zeros((300,500),np.uint8)
    image=image + value
    cv2.imshow(title,image)
    
def onMouse(event,x,y,flags,param):
    global image,bar_name
    if event == cv2.EVENT_RBUTTONDOWN:
        image.fill(0)
        cv2.setTrackbarPos(bar_name,title,image[0][0])
        cv2.imshow(title,image)
        
    elif event == cv2.EVENT_LBUTTONDOWN:
        image.fill(255)
        cv2.setTrackbarPos(bar_name,title,image[0][0])
        cv2.imshow(title,image)
    
image=np.zeros((300,500),np.uint8)

title='Trackbar &Mouse Event'
bar_name='Brightness'
cv2.imshow(title,image)

cv2.createTrackbar(bar_name,title,image[0][0],255,onChange)
cv2.setMouseCallback(title,onMouse)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#직선 및 사각형그리기
import cv2
import numpy as np


blue,green,red = (255,0,0),(0,255,0),(0,0,255)
image=np.zeros((400,600,3),np.uint8) #3채널컬러영상 생성
image[:]=(255,255,255)
pt1,pt2=(50,50),(250,150)
pt3,pt4=(400,150),(500,50)
roi=50,200,200,100

cv2.line(image,pt1,pt2,red)
cv2.line(image,pt3,pt4,green,3,cv2.LINE_AA)

cv2.rectangle(image,pt1,pt2,blue,3,cv2.LINE_4) #4방향연결선
cv2.rectangle(image, roi,red,3,cv2.LINE_8) #내부 체움
cv2.rectangle(image,(400,200,100,100),green,cv2.FILLED) #내부 채움

cv2.imshow('Line&reactangle',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#글자 쓰기
import cv2
import numpy as np

olive,violet,brown=(128,128,0),(221,160,221),(42,42,165)
pt1,pt2=(50,200),(50,260)

image=np.zeros((300,500,3),np.uint8)
image.fill(255)

cv2.putText(image,'SIMPLEX',(50,50),cv2.FONT_HERSHEY_SIMPLEX,2,brown)#2는확대비율,brown 색상
cv2.putText(image,'DUPLEX',(50,130),cv2.FONT_HERSHEY_DUPLEX,3,olive)
cv2.putText(image,'TRUPLEX',pt1,cv2.FONT_HERSHEY_TRIPLEX,2,violet)

fontFace=cv2.FONT_HERSHEY_PLAIN | cv2.FONT_ITALIC
cv2.putText(image,'ITALIC',pt2,fontFace,4,violet)

cv2.imshow('put text',image)
cv2.waitKey(0)

 

#원그리기
import cv2
import numpy as np


orange,blue,cyan = (0,165,255),(255,0,0),(255,255,0)
white,black = (255,255,255),(0,0,0)
image=np.full((300,500,3),white,np.uint8)

center=(image.shape[1]//2,image.shape[0]//2)#영상의 중심 좌표
pt1,pt2=(300,50),(100,220)
shade=(pt2[0]+2,pt2[1]+2)#그림자 좌표

cv2.circle(image,center,100,blue) #원그리기
cv2.circle(image,pt1,50,orange,2)
cv2.circle(image,pt2,70,cyan,-1) #원 내부 채움

font = cv2.FONT_HERSHEY_COMPLEX
cv2.putText(image,'center_blue',center,font,1.0,blue)
cv2.putText(image,'pt1_orange',pt1,font,0.8,orange)
cv2.putText(image,'pt2_cyan',shade,font,1.2,black,2)
cv2.putText(image,'pt2_cyan',pt2,font,1.2,cyan,1)

title='Draw circles'
cv2.namedWindow(title)
cv2.imshow(title,image)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#타원 그리기
import cv2
import numpy as np


orange,blue,white = (0,165,255),(255,0,0),(255,255,255)
image=np.full((300,700,3),white,np.uint8)

pt1,pt2 = (180,150),(550,150) #타원의 중심점
size=(120,60) #타원의크기 -반지름값

cv2.circle(image,pt1,1,0,2) #타원의 중심점(2개의픽셀점) 표시
cv2.circle(image,pt2,1,0,2)

cv2.ellipse(image,pt1,size,0,0,360,blue,1)
cv2.ellipse(image,pt2,size,90,0,360,blue,1)
cv2.ellipse(image,pt1,size,0,30,270,orange,4)
cv2.ellipse(image,pt2,size,90,-45,90,orange,4)

cv2.imshow('Draw Eclipse & Arc ',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#실습문제
import cv2
import numpy as np
import random
rand_data=list()
def makeRandom(cnt):
    global rand_data
    x=random.randint(0,400)
    y=random.randint(0,400)
    rand_data.append([x,y])

for i in range(10):
    makeRandom(400)
    
print(rand_data)
rand_arr=np.array(rand_data)

x_max = max(rand_arr[:,0])
x_max_index=np.argmax(rand_arr[:,0])

x_min= min(rand_arr[:,0])
x_min_index=np.argmin(rand_arr[:,0])

y_max = max(rand_arr[:,1])
y_max_index=np.argmax(rand_arr[:,1])

y_min= min(rand_arr[:,1])
y_min_index=np.argmin(rand_arr[:,1])


#page2

orange,blue,cyan=(0,165,255),(255,0,0),(255,255,0)
white,black = (255,255,255),(0,0,0)

image=np.full((400,400,3),white,np.uint8)
center=(image.shape[1]//2,image.shape[0]//2)
cv2.circle(image,center,25,blue)

for i in range(10):
    print(rand_arr[i][0],rand_arr[i][1])
    cv2.putText(image,'+',(rand_arr[i][0],rand_arr[i][1]),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255))
    
cv2.line(image,rand_data[x_max_index],rand_data[y_min_index],(0,0,255))
cv2.line(image,rand_data[x_max_index],rand_data[y_max_index],(0,0,255))
cv2.line(image,rand_data[x_min_index],rand_data[y_min_index],(0,0,255))
cv2.line(image,rand_data[x_min_index],rand_data[y_max_index],(0,0,255))

title='Ex1'
cv2.imshow(title,image)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

#예제2
import cv2
import numpy as np


def onMouse(event,x,y,flags,param):
    global title,pt
    if event==cv2.EVENT_LBUTTONDOWN:
        if pt[0] <0:
            pt =(x,y)
        else:
            cv2.rectangle(image,pt,(x,y),(255,0,0),2)
            cv2.imshow(title,image)
            pt=(-1,-1)
            
    elif event== cv2.EVENT_RBUTTONDOWN:
        if pt[0]<0: pt=(x,y)
            
        else:
            dx,dy=pt[0]-x,pt[1]-y
            radius=int(np.sqrt(dx*dx+dy*dy))
            cv2.circle(image,pt,radius,(0,0,255),2)
            cv2.imshow(title,image)
            pt=(-1,-1)
            
image=np.full((300,500,3),(255,255,255),np.uint8)
pt=(-1,-1)
title='draw event'
cv2.imshow(title,image)
cv2.setMouseCallback(title,onMouse)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

import cv2

def print_matInfo(name,image):
    if image.dtype=='uint8': mat_type='CV_8U'
    elif image.dtype=='int8': mat_type='CV_8S'
    elif image.dtype=='uint16': mat_type='CV_16U'
    elif image.dtype=='int16': mat_type='CV_16S'
    elif image.dtype=='float32': mat_type='CV_32F'
    elif image.dtype=='float64': mat_type='CV_64F'
    nchannel =3 if image.ndim==3 else 1
    ## depth, channel 출력
    print('%12s: depth(%s),channels(%s)-> mat_type(%sC%d)'%
         (name,image.dtype,nchannel,mat_type,nchannel))

title1,title2 ='gray2gray','gray2color'
gray2gray= cv2.imread('C:/Users/cyan9/read_gray.jpg',cv2.IMREAD_GRAYSCALE)
gray2color=cv2.imread('C:/Users/cyan9/read_gray.jpg',cv2.IMREAD_COLOR)
if (gray2gray is None or gray2color is None):
    raise Exception('영상파일 읽기 에러')

    
print('행렬 좌표 (100,100) 화소값')
print('%s %s'%(title1,gray2gray[100,100]))
print('%s %s\n'%(title2,gray2color[100,100]))
print_matInfo(title1,gray2gray)
print_matInfo(title2,gray2color)
cv2.imshow(title1,gray2gray)
cv2.imshow(title2,gray2color)
cv2.waitKey(0)
cv2.destroyAllWindows()

import sys
sys.path.append('C:\Users\cyan9\common')

import cv2
from common.utils import print_matInfo


title1,title2 ='gray2gray','gray2color'
gray2gray= cv2.imread('C:/Users/cyan9/read_color.jpg',cv2.IMREAD_GRAYSCALE)
gray2color=cv2.imread('C:/Users/cyan9/read_color.jpg',cv2.IMREAD_COLOR)
if (gray2gray is None or gray2color is None):
    raise Exception('영상파일 읽기 에러')
    
print('행렬 좌표 (100,100) 화소값')
print('%s %s'%(title1,gray2gray[100,100]))
print('%s %s\n'%(title2,gray2color[100,100]))

print_matInfo(title1,gray2gray)
print_matInfo(title2,gray2color)
cv2.imshow(title1,gray2gray)
cv2.imshow(title2,gray2color)
cv2.waitKey(0)
cv2.destroyAllWindows()