Interface編集部
10-5Histogram.py
000: import cv2
001: import numpy as np
002:
003: def __main():
004: img = cv2.imread(‘../IMG_0554.JPG’)
005: img = getHist(img)
006:
007: cv2.imshow(“Final result”, img)
008: cv2.waitKey(0)
009: cv2.destroyAllWindows()
010:
011: def getResize(src):
012: global shotSize
013: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
014: height = src.shape[0]
015: width = src.shape[1]
016:
017: largeSize = max(height, width) # 大きい方の辺のサイズ
018: resizeRate = basePixSize / largeSize # 変更比率を計算
019: shotSize = min(height, width) * resizeRate
020: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
021:
022: return dst
023:
024: def getHist(img):
025: img = getResize(img)
026: channel = 3
027: upper = 70
028:
029: size = np.array([upper * 3, 256, channel])
030: blackColor = np.array([0, 0, 0])
031: hist = np.full(size, blackColor, dtype=np.uint8)
032: height, width, _ = hist.shape
033:
034: for j in range(channel):
035: bgrHist = cv2.calcHist(images=[img],channels=[j], mask= None, histSize=[256], ranges=[0, 256]) # (イメージ画,チャンネル,マスク,ビン数(全画素値の場合は256),画素値の範囲(0-255)
036: cv2.normalize(src=bgrHist, dst=bgrHist, alpha=0, beta=upper, norm_type=cv2.NORM_MINMAX) # 最大値50で正規化してピーク値をそろえる
037:
038: color = [0, 0, 0]
039: color[j] = 255
040: baseLine = j * upper + upper
041: for i in range(0, 256):
042: vertical = bgrHist[i]
043: cv2.line(hist, (i, baseLine), (i, baseLine – vertical), color)
044:
045: y = 10
046: x = 10
047: img[y: y + height, x: x + width] = hist
048: return img
049:
050: if __name__ == ‘__main__’:
051: print(cv2.__version__)
052:
053: shotSize = 0
054: __main()