오늘로 OpenCV를 마무리하고 본격적인 AI Machine Learning 파트에 들어갔다. 첫 내용으로는 PyTorch부터 시작하였다.
pip install ultralytics or conda install -c conda-forge pytorch torchvision -> conda install -c conda-forge ultralyticsfrom ultralytics import YOLOconf= : 정확도 / 신뢰도model = YOLO("yolo11n.pt")
img = cv.imread("../images/person_dog.jpg")
# 객체 인식
results = model.predict(img, conf=0.5)
# 탐지 결과를 이미지 위에 그려줌
annotated_frame = results[0].plot()
cv.imshow("img", annotated_frame)
cv.waitKey(0)
cv.destroyAllWindows()
cv.waitKey(1)
cap = cv.VideoCapture("../videos/cars.mp4")
model = YOLO("yolo11n.pt")
fps = cap.get(cv.CAP_PROP_FPS)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
result = model.predict(frame, conf=0.5)
annotated_frame = result[0].plot()
cv.imshow("cars", annotated_frame)
if cv.waitKey(int(1000/fps)) == ord("q"):
break
cap.release()
cv.destroyAllWindows()
cv.waitKey(1)
cap = cv.VideoCapture(0)
model = YOLO("yolo11n.pt")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
result = model.predict(frame, conf=0.5)
annotated_frame = result[0].plot()
cv.imshow("video", annotated_frame)
if cv.waitKey(1) == ord("q"):
break
cap.release()
cv.destroyAllWindows()
cv.waitKey(1)
brew install tesseractbrew install tesseract-langpip install pytesseractpyt.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe”pyt.tesseract_cmd = r'/usr/local/bin/tesseract‘img = cv.imread("../images/bill.png", cv.IMREAD_GRAYSCALE)
ret, binary = cv.threshold(img, -1, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
text = pyt.image_to_string(binary, lang="kor+eng")
print(text)
pip3 install torch torchvisionconda install pytorch torchvision -c pytorchimport torch
import torchvision
torch : 메인 네임스페이스, 텐서 등의 다양한 함수가 포함torch.autograd : 자동 미분 기능을 제공하는 라이브러리torch.nn : 신경망 구축을 위한 데이터 구조, 레이어 등을 제공하는 라이브러리torch.multiprocessing : 병렬처리 기능을 제공하는 라이브러리torch.optim : SGD(Stochastic Gradient Descent, 확률적 경사 하강법) 등 파라미터 최적화 알고리즘 제공torch.utils``` : 데이터 조작 등 유틸리티 기능 제공empty() : 메모리에 남아있는 쓰레기값으로 채워진 텐서 생성x = torch.empty(4, 2)
print(x)
# tensor([[8.4078e-45, 0.0000e+00],
# [0.0000e+00, 0.0000e+00],
# [1.1388e-38, 1.5574e-41],
# [0.0000e+00, 0.0000e+00]])
rand() : 0과 1사이의 값으로 랜덤하게 초기화된 텐서randn() : 표준정규분포를 따르는 랜덤한 값으로 초기화된 텐서 생성x = torch.rand(4,2)
y = torch.randn(2,3)
print(x)
print(y)
# tensor([[0.4590, 0.9777],
# [0.1977, 0.6261],
# [0.0530, 0.9501],
# [0.1548, 0.1872]])
# tensor([[ 1.4518, -0.5593, 0.6369],
# [-0.1235, 0.2759, 0.1233]])
x = torch.zeros(4,2, dtype=torch.long)
print(x)
# tensor([[0, 0],
# [0, 0],
# [0, 0],
# [0, 0]])
x = torch.ones(2,4, dtype=torch.double)
print(x)
# tensor([[1., 1., 1., 1.],
# [1., 1., 1., 1.]], dtype=torch.float64)
new_ones() : 기존 텐서의 속성(데이터 타입, 장치)을 물려받음y = x.new_ones(3,2)
print(y)
# tensor([[1., 1.],
# [1., 1.],
# [1., 1.]], dtype=torch.float64)
x = torch.tensor([1, 2.5])
print(x)
# tensor([1.0000, 2.5000])
from_numpy()data = [1,2,3,4]
np_array = np.array(data)
x = torch.from_numpy(np_array)
print(x)
# tensor([1, 2, 3, 4])
x = torch.tensor([[1,2], [3,4]], dtype=torch.float64)
y = torch.zeros_like(x)
print(y)
# tensor([[0., 0.],
# [0., 0.]], dtype=torch.float64)
t = torch.rand(3,4)
print(t.size()) # 모양
# torch.Size([3, 4])
print(t.shape) # 모양
# torch.Size([3, 4])
print(t.dtype) # 자료형
# torch.float32
print(t.device) # 장치
# cpu
x = torch.FloatTensor([1,2,3])
y = torch.tensor([1,2,3], dtype=torch.float32)
print(x.dtype)
print(y.dtype)
# torch.float32
# torch.float32
ft = torch.FloatTensor([1.1, 2.2, 3.3])
print(ft)
print(ft.short())
print(ft.int())
print(ft.long())
# tensor([1.1000, 2.2000, 3.3000])
# tensor([1, 2, 3], dtype=torch.int16)
# tensor([1, 2, 3], dtype=torch.int32)
# tensor([1, 2, 3])
it = torch.IntTensor([1,2,3])
print(it)
print(it.half())
print(it.float())
print(it.double())
# tensor([1, 2, 3], dtype=torch.int32)
# tensor([1., 2., 3.], dtype=torch.float16)
# tensor([1., 2., 3.])
# tensor([1., 2., 3.], dtype=torch.float64)
x = torch.randn(1)
if torch.cuda.is_available():
tensor = x.to("cuda")
tensor.device
# device(type='cuda', index=0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
# cuda
x = torch.ones(2,3, device=device)
t0 = torch.tensor(0)
print(t0.ndim)
print(t0.shape)
# 0
# torch.Size([])
t1 = torch.tensor([1,2,3])
print(t1.ndim)
print(t1.shape)
# 1
# torch.Size([3])
t2 = torch.tensor([[1,2,3], [1,2,3], [1,2,3]])
print(t2.ndim)
print(t2.shape)
# 2
# torch.Size([3, 3])
t3 = torch.tensor([[[1,2,3], [1,2,3], [1,2,3]],
[[1,2,3], [1,2,3], [1,2,3]],
[[1,2,3], [1,2,3], [1,2,3]]])
print(t3.ndim)
print(t3.shape)
# 3
# torch.Size([3, 3, 3])
t4 = torch.tensor(
[[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]],
[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]]]
)
print(t4.ndim)
print(t4.shape)
# 4
# torch.Size([2, 3, 3, 3])
t5 = torch.tensor(
[[[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]],
[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]]],
[[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]],
[[[1,2,3], [1,2,3], [1,2,3]], [[1,2,3], [1,2,3], [1,2,3]]]]]
)
print(t5.ndim)
print(t5.shape)
# 5
# torch.Size([2, 2, 2, 3, 3])
PyTorch는 NumPy와 매우 유사한 점이 많아서 아직은 크게 어려운 내용은 없었다. NumPy 복습과 수학 공부를 계속한다면 앞으로의 Machine Learning 파트를 순조롭게 배울 수 있을 것 같다.