"""
카메라로 사진을 찍고 이미지를 편집합니다.
Class:
:obj:`~openpibo.vision_camera.Camera`
"""
import cv2,requests
import os
import time
import threading
import numbers
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from picamera2 import Picamera2
#from libcamera import Transform
import openpibo_models
import logging
os.environ['LIBCAMERA_LOG_LEVELS'] = '3'
[docs]
class Camera:
"""
Functions:
:meth:`~openpibo.vision_camera.Camera.usb_cameras`
:meth:`~openpibo.vision_camera.Camera.imread`
:meth:`~openpibo.vision_camera.Camera.read`
:meth:`~openpibo.vision_camera.Camera.release`
:meth:`~openpibo.vision_camera.Camera.create_matte`
:meth:`~openpibo.vision_camera.Camera.imshow`
:meth:`~openpibo.vision_camera.Camera.imshow_to_ide`
:meth:`~openpibo.vision_camera.Camera.resize`
:meth:`~openpibo.vision_camera.Camera.rotate`
:meth:`~openpibo.vision_camera.Camera.imwrite`
:meth:`~openpibo.vision_camera.Camera.draw_bitmap`
:meth:`~openpibo.vision_camera.Camera.rectangle`
:meth:`~openpibo.vision_camera.Camera.circle`
:meth:`~openpibo.vision_camera.Camera.line`
:meth:`~openpibo.vision_camera.Camera.putTextPIL`
:meth:`~openpibo.vision_camera.Camera.putText`
:meth:`~openpibo.vision_camera.Camera.stylization`
:meth:`~openpibo.vision_camera.Camera.detailEnhance`
:meth:`~openpibo.vision_camera.Camera.pencilSketch`
:meth:`~openpibo.vision_camera.Camera.edgePreservingFilter`
:meth:`~openpibo.vision_camera.Camera.flip`
카메라로 사진을 찍고 이미지를 편집합니다.
* ``Camera()`` (``cam=0``) 는 보드 카메라, ``Camera(1)`` · ``Camera(2)`` 는 USB 카메라입니다(V4L2 를 지원하면 기종 상관없음).
USB 카메라 번호는 꽂힌 카메라의 USB 포트 순서이고, :meth:`~openpibo.vision_camera.Camera.usb_cameras` 로 볼 수 있습니다.
* 보드 카메라는 처음 :meth:`~openpibo.vision_camera.Camera.read` 를 부를 때 엽니다. 그래서 카메라를 못 열 때의 오류는 ``read()`` 에서 납니다.
* ``read()`` 는 크기를 주지 않으면 640x480 그림을 돌려줍니다. USB 카메라도 같은 크기이고, 카메라 비율이 다르면 가운데를 잘라 맞춥니다.
* 이미지에 도형/글자를 추가할 수 있습니다.
* 이미지를 변환할 수 있습니다.
example::
from openpibo.vision_camera import Camera
camera = Camera() # 보드 카메라
# camera = Camera(1) # USB 카메라 cam1
# 아래의 모든 예제 이전에 위 코드를 먼저 사용합니다.
"""
def __init__(self, cam=0, width=None, height=None):
"""
Camera 클래스를 초기화합니다.
:param int cam: 쓸 카메라. ``0`` 은 보드 카메라(기본), ``1`` 부터는 USB 카메라(V4L2 를 지원하면 기종 상관없음,
꽂은 USB 포트 순서 — :meth:`~openpibo.vision_camera.Camera.usb_cameras` 로 볼 수 있습니다).
USB 카메라는 크기를 주지 않으면 640x480 이고, 카메라 비율이 다르면 가운데를 잘라 맞춥니다
:param int width: ``read()`` 가 돌려줄 그림의 가로(px). 없으면 640
:param int height: ``read()`` 가 돌려줄 그림의 세로(px). 없으면 480
하나만 주면 다른 쪽은 기본 비율(640:480)로 맞춥니다.
"""
self.usb = self._cam_no(cam) # 0 = 보드 카메라, 1~ = USB 카메라(261120)
self.width, self.height = 640, 480 # USB 카메라도 같은 크기(비율이 다르면 가운데를 잘라 맞춤)
if width is not None or height is not None:
w = self._size(width, 'width') if width is not None else None
h = self._size(height, 'height') if height is not None else None
if w is None:
w = max(1, int(round(h * self.width / self.height)))
if h is None:
h = max(1, int(round(w * self.height / self.width)))
self.width, self.height = w, h
cv2.setUseOptimized(True)
cv2.setNumThreads(cv2.getNumberOfCPUs())
self._open_lock = threading.Lock()
if self.usb:
from .modules.usbcam import UsbCam
self.cap = UsbCam(self.usb - 1, self.width, self.height)
return
# 보드 카메라는 여기서 열지 않는다 — 처음 read() 때 _open_board()(261120)
self.cap = None
def _open_board(self):
# 보드 카메라는 처음 read() 할 때 연다(261120). 그리기·보여주기 블록도 camera = Camera() 를 넣어서,
# USB 카메라만 쓰는 프로그램까지 보드 카메라를 열지 않게. 두 스레드가 처음 read 를 같이 불러도 한 번만 연다
with self._open_lock:
if self.cap is not None:
return
# 앞 프로그램·도구 서비스가 카메라를 막 놓는 중이면 'Failed to start camera' 가 날 수 있다.
# 1초씩 쉬며 세 번까지 해 본다(261119). 카메라가 아예 안 잡히면(IndexError) 바로 오류
cap = None
for attempt in range(3):
try:
cap = Picamera2(self._board_num())
config = cap.create_still_configuration(
main={
'size': (1280, 960),
'format': 'RGB888'
},
#transform=Transform(hflip=False, vflip=False),
buffer_count=2
)
cap.configure(config)
cap.set_controls({'AwbEnable': True, 'AwbMode': 0})
cap.start()
break
except (RuntimeError, IndexError) as ex:
if cap is not None:
try:
cap.close()
except Exception as close_err: # 열다 만 카메라라 닫기도 실패할 수 있다 — 다시 여는 데는 지장 없다
logging.debug('camera close after failed start: %s', close_err)
cap = None
if attempt == 2 or isinstance(ex, IndexError):
raise
time.sleep(1.0)
self.cap = cap
@staticmethod
def _board_num():
# libcamera 는 USB(UVC) 카메라도 카메라로 센다(261120 PiBrain: 0 ov5647, 1 USB 2.0 PC Cam).
# 순서에 기대지 않고 USB 가 아닌 첫 카메라(보드 카메라)를 연다
for c in Picamera2.global_camera_info():
if 'usb' not in str(c.get('Id', '')).lower():
return c.get('Num', 0)
raise IndexError('보드 카메라를 찾지 못했어요 / The board camera was not found')
@staticmethod
def _cam_no(cam):
if type(cam) is bool or not isinstance(cam, numbers.Integral): # numpy 정수도 받는다
raise ValueError('"cam" must be integer type')
if not 0 <= cam <= 9:
raise ValueError('"cam" must be 0~9')
return int(cam)
[docs]
@staticmethod
def usb_cameras():
"""
꽂혀 있는 USB 카메라 목록을 돌려줍니다. 보드 카메라는 들어가지 않습니다.
example::
Camera.usb_cameras()
# [{'cam': 1, 'dev': '/dev/video1', 'name': 'USB Camera: USB Camera'}]
:returns: ``cam`` (``Camera(cam=…)`` 에 넣을 번호) · ``dev`` (장치 파일) · ``name`` (카메라가 알려 준 이름) 의 목록
"""
from .modules.usbcam import list_usb
return [{'cam': i + 1, 'dev': c['dev'], 'name': c['name']} for i, c in enumerate(list_usb())]
@staticmethod
def _size(v, name):
if type(v) is bool:
raise ValueError(f'"{name}" must be a positive integer')
try:
n = int(round(float(v)))
except (TypeError, ValueError, OverflowError):
raise ValueError(f'"{name}" must be a positive integer')
if n <= 0:
raise ValueError(f'"{name}" must be a positive integer')
return n
[docs]
def release(self):
"""
카메라를 놓습니다. 다른 프로그램이 같은 카메라를 쓸 수 있게 됩니다.
놓은 뒤에 다시 ``read()`` 하면 다시 엽니다.
"""
if self.cap is not None and self.usb:
self.cap.close()
self.cap = None
if self.cap is not None:
self.cap.stop()
self.cap.close()
self.cap = None
[docs]
def imread(self, filename):
"""
이미지 파일을 읽습니다.
:param str filename: 사용할 이미지 파일
:returns: ``numpy.ndarray`` 타입 이미지 객체
"""
return cv2.imread(filename)
[docs]
def read(self):
"""
카메라로 사진을 찍습니다.
보드 카메라는 처음 부를 때 엽니다(앞 프로그램이 카메라를 막 놓는 중이면 1초씩 쉬며 세 번까지 해 봅니다).
USB 카메라는 읽다가 실패하면(뽑았다 꽂음 등) 한 번 다시 찾아 엽니다.
:returns: ``numpy.ndarray`` 타입 이미지 객체(BGR)
"""
if self.usb:
if self.cap is None: # release() 뒤에 다시 읽으면 다시 연다
from .modules.usbcam import UsbCam
self.cap = UsbCam(self.usb - 1, self.width, self.height)
return self.cap.read()
if self.cap is None:
self._open_board()
return cv2.resize(cv2.flip(self.cap.capture_array(), -1), (self.width, self.height))
# return cv2.rotate(cv2.resize(self.cap.capture_array(), (self.height, self.width)),cv2.ROTATE_90_COUNTERCLOCKWISE)
# return cv2.rotate(self.cap.capture_array(),cv2.ROTATE_90_COUNTERCLOCKWISE)
[docs]
def create_matte(self, colors=(255,255,255)):
"""
한 가지 색으로 채운 빈 이미지(매트)를 만듭니다. 크기는 ``read()`` 와 같습니다. 카메라는 열지 않습니다.
example::
img = camera.create_matte((255, 255, 255)) # 흰 바탕
img = camera.create_matte('#ff0000') # 빨간 바탕
:param tuple or str colors: 색 — (b, g, r) 튜플 또는 ``'#rrggbb'`` 글자
:returns: ``numpy.ndarray`` 타입 이미지 객체
"""
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
return np.full((self.height, self.width, 3), colors, dtype=np.uint8)
[docs]
def imshow(self, img, ratio=1.0):
"""
이미지 파일을 Web IDE에 출력합니다.
:param numpy.ndarray img: 이미지 객체
:param float ratio: 이미지 사이즈 변환 비율 (다수 동시 사용시, 네트워크 부하)
"""
self.imshow_to_ide(img, ratio)
[docs]
def imshow_to_ide(self, img, ratio=0.25):
"""
이미지 파일을 Web IDE에 출력합니다.
:param numpy.ndarray img: 이미지 객체
:param float ratio: 이미지 사이즈 변환 비율 (다수 동시 사용시, 네트워크 부하)
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
img = cv2.resize(img, (0, 0), fx=ratio, fy=ratio, interpolation=cv2.INTER_AREA)
# curl -X 'POST' -so /dev/null 'http://0.0.0.0/show' -H 'accept: application/json' -H 'Content-Type: multipart/form-data' -F 'data=@{filename};type=image/png'
requests.post('http://0.0.0.0/show', headers={'accept': 'application/json'}, files={'data': ('filename', cv2.imencode('.jpg', img)[1].tobytes(), 'image/png')})
[docs]
def resize (self, img, w, h):
"""
Opencv 이미지의 크기를 변환합니다.
:param numpy.ndarray img: 이미지 객체
:param int w: 변환될 이미지의 가로 크기입니다. (픽셀 단위)
:param int h: 변환될 이미지의 세로 크기입니다. (픽셀 단위)
:returns: 크기 변환 후의 ``numpy.ndarray`` 이미지 객체
"""
return cv2.resize(img, (w, h))
[docs]
def rotate(self, img, degree=10, ratio=0.9):
"""
이미지를 회전시킵니다.
:param numpy.ndarray img: 이미지 객체
:param int degree: 회전할 각도
:param float ratio: 축소 또는 확대할 비율 (0보다 큰 숫자. 1.0 보다 작으면 축소, 크면 확대)
:returns: 회전한 ``numpy.ndarray`` 이미지 객체
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(degree) is not int or abs(degree) >= 360:
raise Exception(f'"{degree}" must be integer type and -359~359')
if type(ratio) not in (int, float) or ratio <= 0:
raise Exception(f'"{ratio}" must be a number greater than 0')
rows, cols = img.shape[0:2]
op = cv2.getRotationMatrix2D((cols/2,rows/2), degree, ratio)
return cv2.warpAffine(img, op, (cols,rows))
[docs]
def imwrite(self, filename, img):
"""
이미지를 파일로 저장합니다.
:param str filename: 저장할 파일 경로(jpg, png)
:param numpy.ndarray img: 저장할 이미지 객체
"""
return cv2.imwrite(filename, img)
[docs]
def draw_bitmap(self, w, h, val, background=(255,255,255), pixel=(0,0,0)):
"""
비트맵(점 그림) 데이터를 이미지로 만듭니다. 카메라 화면 크기로 키웁니다.
:param int w: bitmap 가로 길이
:param int h: bitmap 세로 길이
:param tuple background: 배경 색상
:param tuple pixel: 비트 색상
:returns: ``numpy.ndarray`` 이미지 객체
"""
# 1. 문자열을 정수 리스트로 변환
try:
values = [int(v.strip()) for v in val.split(',')]
except ValueError:
raise ValueError("val 은 쉼표로 나눈 정수 글자여야 해요 / val must be comma-separated integers")
# 2. w*h 크기에 맞는 값인지 확인
if len(values) != w * h:
raise ValueError(f"val 의 개수가 w*h 와 달라요 / val length must be w*h: {len(values)} != {w * h}")
# 3. 1차원 리스트를 2차원 배열로 변환 (행: h, 열: w)
bitmap = np.array(values).reshape((h, w))
# 4. 작은 크기의 이미지 생성 (배경색으로 채움)
small_img = np.full((h, w, 3), background, dtype=np.uint8)
small_img[bitmap == 1] = pixel # bitmap 값이 1인 부분에 pixel 색상 적용
# 5. 각 픽셀을 복제할 배수 계산 (정수 배수)
# 결과는 카메라 그림과 같은 크기(가로 self.width x 세로 self.height). 전엔 가로·세로를 바꿔 써서
# 파이보는 세로 480x640, PiBrain 은 가로 640x480 이 나왔다(LCD·OLED 는 다시 늘려 그려서 티가 안 났다, 260930)
scale_y = self.height // h # 세로 복제 횟수
scale_x = self.width // w # 가로 복제 횟수
# 6. np.repeat를 이용하여 픽셀 복제 (각 픽셀을 scale_y x scale_x 블록으로 확장)
replicated_img = np.repeat(np.repeat(small_img, scale_y, axis=0), scale_x, axis=1)
# 7. 복제 결과가 정확히 카메라 그림 크기가 아닐 수 있으므로, 부족한 부분은 배경색으로 채우고
# 넘치는 부분은 자른다.
rep_h, rep_w = replicated_img.shape[:2]
if rep_h < self.height or rep_w < self.width:
pad_bottom = max(self.height - rep_h, 0)
pad_right = max(self.width - rep_w, 0)
final_img = cv2.copyMakeBorder(replicated_img, 0, pad_bottom, 0, pad_right, cv2.BORDER_CONSTANT, value=background)
else:
final_img = replicated_img[:self.height, :self.width]
return final_img
[docs]
def rectangle(self, img, p1, p2, colors=(255,255,255), tickness=1):
"""
이미지에 직사각형을 그립니다.
:param numpy.ndarray img: 이미지 객체
:param tuple(int, int) p1: 좌측상단 좌표 (x, y)
:param tuple(int, int) p2: 우측하단 좌표 (x, y)
:param tuple(int, int, int) colors: BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
:param int tickness: 사각형 모서리의 두께 (픽셀 단위) -1 은 채움
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(p1) is not tuple:
raise Exception(f'"{p1}" must be tuple type')
if len(p1) != 2:
raise Exception(f'len({p1}) must be 2')
if type(p2) is not tuple:
raise Exception(f'"{p2}" must be tuple type')
if len(p2) != 2:
raise Exception(f'len({p2}) must be 2')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
return cv2.rectangle(img, p1, p2, colors, tickness)
[docs]
def circle(self, img, p, r, colors=(255,255,255), tickness=1):
"""
이미지에 원을 그립니다.
:param numpy.ndarray img: 이미지 객체
:param tuple(int, int) p: 좌측상단 좌표 (x, y)
:param int r: 반지름
:param tuple(int, int, int) colors: BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
:param int tickness: 원 테두리의 두께 (픽셀 단위) -1은 채움
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(p) is not tuple:
raise Exception(f'"{p}" must be tuple type')
if len(p) != 2:
raise Exception(f'len({p}) must be 2')
if type(r) is not int:
raise Exception(f'"{r}" must be integer type')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
return cv2.circle(img, p, r, colors, tickness)
[docs]
def line(self, img, p1, p2, colors=(255,255,255), tickness=1):
"""
이미지에 직선을 그립니다.
:param numpy.ndarray img: 이미지 객체
:param tuple(int, int) p1: 시작 좌표 (x, y)
:param tuple(int, int) p2: 끝 좌표 (x, y)
:param tuple(int, int, int) colors: BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
:param int tickness: 선의 두께 (픽셀 단위)
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(p1) is not tuple:
raise Exception(f'"{p1}" must be tuple type')
if len(p1) != 2:
raise Exception(f'len({p1}) must be 2')
if type(p2) is not tuple:
raise Exception(f'"{p2}" must be tuple type')
if len(p2) != 2:
raise Exception(f'len({p2}) must be 2')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
return cv2.line(img, p1, p2, colors, tickness)
[docs]
def putTextPIL(self, img, text, points, size=30, colors=(255,255,255)):
"""
이미지에 문자를 입력합니다. (한/영 가능 - pillow 이용)
:param numpy.ndarray img: 이미지 객체
:param str text: 표시할 문자열
:param tuple(int, int) points: 텍스트 블록 좌측상단 좌표 (x, y)
:param int size: 표시할 글자의 크기
:param tuple(int, int, int) colors: 글자 색깔 BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(points) is not tuple:
raise Exception(f'"{points}" must be tuple type')
if len(points) != 2:
raise Exception(f'len({points}) must be 2')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
font = ImageFont.truetype(openpibo_models.filepath("KDL.ttf"), size)
pil = Image.fromarray(img) # CV to PIL
ImageDraw.Draw(pil).text(points, text, font=font, fill=colors) # putText
img[:] = np.array(pil) # PIL to CV
return img
[docs]
def putText(self, img, text, points, size=1, colors=(255,255,255), tickness=1):
"""
이미지에 문자를 입력합니다. (영어만 가능)
:param numpy.ndarray img: 이미지 객체
:param str text: 표시할 문자열
:param tuple(int, int) points: 텍스트 블록 좌측하단 좌표 (x, y)
:param int size: 표시할 글자의 크기
:param tuple(int, int, int) colors: 글자 색깔 BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
:param int tickness: 글자 두께
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(points) is not tuple:
raise Exception(f'"{points}" must be tuple type')
if len(points) != 2:
raise Exception(f'len({points}) must be 2')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
return cv2.putText(img, text, points, cv2.FONT_HERSHEY_SIMPLEX, size, colors, tickness)
[docs]
def stylization(self, img, sigma_s=100, sigma_r=0.5):
"""
만화 이미지로 변환합니다. (opencv api) low speed
:param numpy.ndarray img: 이미지 객체
:param float sigma_s: 이미지의 blur 보존 정도 (1-200)
:param float sigma_r: 이미지의 Edge 적용 정도 (0-1)
:returns: ``numpy.ndarray`` 이미지 객체
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
return cv2.stylization(img, sigma_s=sigma_s, sigma_r=sigma_r)
[docs]
def detailEnhance(self, img, sigma_s=100, sigma_r=0.05):
"""
만화 이미지로 변환합니다. (opencv api)
:param numpy.ndarray img: 이미지 객체
:param float sigma_s: 이미지의 blur 보존 정도 (1-200)
:param float sigma_r: 이미지의 Edge 적용 정도 (0-1)
:returns: ``numpy.ndarray`` 이미지 객체
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
return cv2.detailEnhance(img, sigma_s=sigma_s, sigma_r=sigma_r)
[docs]
def pencilSketch(self, img, sigma_s=100, sigma_r=0.2, shade_factor=0.018):
"""
스케치 이미지로 변환합니다.
example::
img = camera.read()
camera.sketchize(img)
:param numpy.ndarray img: 이미지 객체
:param float sigma_s: 이미지의 blur 보존 정도 (1-200)
:param float sigma_r: 이미지의 Edge 적용 정도 (0-1)
:param float shade_factor: 이미지의 밝기 정도 (0-0.1)
:returns: ``numpy.ndarray`` 이미지 객체 / grayscale, bgr
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
return cv2.pencilSketch(img, sigma_s=sigma_s, sigma_r=sigma_r, shade_factor=shade_factor)
[docs]
def edgePreservingFilter(self, img, flags=1, sigma_s=60, sigma_r=0.4):
"""
흐림 이미지로 변환합니다.
:param numpy.ndarray img: 이미지 객체
:param int flags: 필터 종류 1 (RECURS_FILTER) or 2 (NORMCONV_FILTER)
:param float sigma_s: 이미지의 blur 보존 정도 (1-200)
:param float sigma_r: 이미지의 Edge 적용 정도 (0-1)
:returns: ``numpy.ndarray`` 이미지 객체
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
return cv2.edgePreservingFilter(img, flags=flags, sigma_s=sigma_s, sigma_r=sigma_r)
[docs]
def flip(self, img, flags=1):
"""
상하/좌우 대칭 이미지로 변환합니다
:param numpy.ndarray img: 이미지 객체
:param int flags: 0: 상하 대칭, 1: 좌우 대칭, -1: 상하/좌우 대칭
:returns: ``numpy.ndarray`` 이미지 객체
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
return cv2.flip(img, flags)