8-1Encode.py

000: import cv2
001: import sys
002:
003: def __main():
004: img = cv2.imread(‘DSC_0071.JPG’)
005: img = getResize(img)
006: matImg = img.copy()
007:
008: # Jpegに変換
009: result, jpgImg = cv2.imencode(‘.jpg’, img=img, params=[int(cv2.IMWRITE_JPEG_QUALITY), 80]) # 0 – 100
010:
011: # PNGに変換
012: result, pngImg = cv2.imencode(‘.png’, img=img, params=[int(cv2.IMWRITE_PNG_COMPRESSION), 8]) # 0 – 9
013:
014: # TIFFに変換
015: result, tifImg = cv2.imencode(‘.tif’, img=img, params=[int(cv2.IMWRITE_TIFF_COMPRESSION)])
016:
017: print(“Mat size = {0}”.format(sys.getsizeof(img)))
018: print(“Jpeg size = {0}”.format(sys.getsizeof(jpgImg)))
019: print(“PNG size = {0}”.format(sys.getsizeof(pngImg)))
020: print(“TIFF size = {0}”.format(sys.getsizeof(tifImg)))
021:
022: jpgImg = cv2.imdecode(jpgImg, cv2.IMREAD_COLOR)
023: pngImg = cv2.imdecode(pngImg, cv2.IMREAD_COLOR)
024: tifImg = cv2.imdecode(tifImg, cv2.IMREAD_COLOR)
025:
026: cv2.imshow(‘Original’, matImg)
027: cv2.imshow(‘Jpeg’, jpgImg)
028: cv2.imshow(‘Png’, pngImg)
029: cv2.imshow(‘Tiff’, tifImg)
030:
031: cv2.waitKey(0)
032: cv2.destroyAllWindows()
033:
034: def getResize(src):
035: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
036: height = src.shape[0]
037: width = src.shape[1]
038:
039: largeSize = max(height, width) # 大きい方の辺のサイズ
040: resizeRate = basePixSize / largeSize # 変更比率を計算
041: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
042:
043: return dst
044:
045: if __name__ == ‘__main__’:
046: print(cv2.__version__)
047:
048: __main()