GitHubリポジトリ
https://github.com/kyatou/python-opencv_tutorial
今日はROIの設定と、画像のエンコード・デコードです。
画像全体に処理を行うと時間がかかるので、特定の領域(ROI)を作成してROIだけに処理を行うと処理時間の短縮が可能になります。
''' python-opencv tutorial Create image ROI(Region of Interest) Usage: 07_image_roi.py imagename ''' #import opencv library import cv2 import sys import numpy argvs=sys.argv if (len(argvs) != 2): print 'Usage: # python %s imagefilename' % argvs[0] quit() imagefilename = argvs[1] try: img=cv2.imread(imagefilename, 1) except: print 'faild to load %s' % imagefilename quit() imgshape=img.shape roiWidth=imgshape[1]/4 roiHeight=imgshape[0]/4 sx=imgshape[1]/2-roiWidth sy=imgshape[0]/2-roiHeight ex=imgshape[1]/2+roiWidth ey=imgshape[0]/2+roiHeight #extract roi as array roi=img[sy:ey,sx:ex] #invert roi area img[sy:ey,sx:ex]=cv2.bitwise_not(roi) cv2.imshow('roi image',img) cv2.waitKey(0) cv2.destroyAllWindows()
画像のエンコード・デコードは、OpenCVの画像形式のものを他のアプリケーションでも読める形式(jpeg,pngなど)に 変換したり、その逆を行う作業です。ファイルに保存する場合はimwriteを使いますが、メモリ上に格納したい時はimencodeを使用します。例えばWebカメラ画像をキャプチャして、ネットワーク経由で他のPCに転送して表示したかったりするときにエンコード・デコードがあると便利です。
''' python-opencv tutorial Encode and decode image data. Usage: 08_image_encode_decode.py imagename ''' #import opencv library import cv2 import sys import numpy argvs=sys.argv if (len(argvs) != 2): print 'Usage: # python %s imagefilename' % argvs[0] quit() imagefilename = argvs[1] try: img=cv2.imread(imagefilename, 1) except: print 'faild to load %s' % imagefilename quit() #encode to jpeg format #encode param image quality 0 to 100. default:95 #if you want to shrink data size, choose low image quality. encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90] result,encimg=cv2.imencode('.jpg',img,encode_param) if False==result: print 'could not encode image!' quit() #decode from jpeg format decimg=cv2.imdecode(encimg,1) cv2.imshow('Source Image',img) cv2.imshow('Decoded image',decimg) cv2.waitKey(0) cv2.destroyAllWindows()
ではまた。
0 件のコメント:
コメントを投稿