2020년 7월 9일 목요일

[python] OpenCv example

1. Open CV install

python -m pip install opencv-python



2. Image Load
import cv2
im = cv2.imread('lena.jpg')


3. Concatenate images of same width vertically

im_v = cv2.vconcat([im1, im1])
cv2.imwrite('vimage.jpg', im_v)


4. Concatenate images of same height horizontally

im_h = cv2.hconcat([im1, im1])
cv2.imwrite('himage.jpg', im_h)


5. Merge vertically


import os
import codecs
import numpy as np
import cv2
from PIL import Image

def cv2_imread( filePath ) :
 with open( filePath.encode("utf-8"), "rb") as f:
  image = bytearray(f.read())
  nparray = np.asarray(image, dtype = np.uint8)
  return cv2.imdecode(nparray , cv2.IMREAD_UNCHANGED)

def cv2_imread2( filePath ) :
 with open( filePath.encode("utf-8"), 'rb') as f:
  image = f.read()
  nparray = np.fromstring(image, dtype = np.uint8)
  return cv2.imdecode(nparray , cv2.IMREAD_UNCHANGED)

def cv2_imwrite( filePath, cv_image ) :
 rv, im_jpg = cv2.imencode( filePath[-4:], cv_image)
 with open( filePath, 'wb') as f:
  f.write(im_jpg.tobytes())
 

image_list = []

if __name__ == "__main__":
 base_dir = r"D:\Temp2\수화"
 sub_dirs = os.listdir(base_dir)
 for sub_dir in sub_dirs:
  sub_dir_path = os.path.join(base_dir,sub_dir)
  image_files = os.listdir(sub_dir_path)
  for image_file in image_files:
   image_file_name = os.path.join(sub_dir_path,image_file)
   print(image_file_name )
   image_list.append(cv2_imread(image_file_name))
  image_merged = cv2.vconcat( image_list )
  merged_file_name = sub_dir_path + '.png'
  print( '->', merged_file_name)
  cv2_imwrite(merged_file_name, image_merged)







댓글 없음:

댓글 쓰기