2-3Binary.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004:
005: img = createImage()
006: cv2.imshow(‘Orignal’, img)
007:
008: # ここで処理を実行する
009: img = getBinary(img)
010:
011: cv2.imshow(‘Final result’, img)
012: cv2.waitKey(0)
013:
014: cv2.destroyAllWindows()
015:
016: def getBinary(src):
017: “””CPUを使用”””
018: # 閾値(thresh)以下の値は0に,それ以外はmaxValで指定した値になる
019: ret, c_dst = cv2.threshold(src, thresh=128, maxval=255, type=cv2.THRESH_BINARY)
020: cv2.imshow(‘Bunary Color’, c_dst)
021:
022: src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) # グレースケールに変換する
023: cv2.imshow(‘Gray’, src)
024: # 閾値(thresh)以下の値は0に,それ以外はmaxValで指定した値になる
025: ret, dst = cv2.threshold(src, thresh=128, maxval=255, type=cv2.THRESH_BINARY)
026:
027: return dst
028:
029: def createImage():
030:
031: width = 600
032: height = 480
033:
034: size = (height, width, 3) # 縦480ピクセル 横640ピクセル 3チャンネル
035: img = np.zeros(size, dtype=np.uint8)
036: rete = 255 / width
037: for h in range(0, height):
038: for w in range(0, width):
039: data = int(w * rete)
040: img[h, w] = [data, data, data]
041:
042: red = np.array([0., 0., 255.])
043: green = np.array([0., 255., 0.])
044: blue = np.array([255., 0., 0.])
045:
046: cyan = np.array([255., 255., 0.])
047: magenta = np.array([255., 0., 255])
048: yellow = np.array([0., 255., 255.])
049:
050: cv2.rectangle(img=img, pt1=(0, 0), pt2=(200, 200), color=red, thickness=-1)
051: cv2.rectangle(img=img, pt1=(200, 0), pt2=(400, 200), color=green, thickness=-1)
052: cv2.rectangle(img=img, pt1=(400, 0), pt2=(600, 200), color=blue, thickness=-1)
053:
054: cv2.rectangle(img=img, pt1=(0, 200), pt2=(200, 400), color=cyan, thickness=-1)
055: cv2.rectangle(img=img, pt1=(200, 200), pt2=(400, 400), color=magenta, thickness=-1)
056: cv2.rectangle(img=img, pt1=(400, 200), pt2=(600, 400), color=yellow, thickness=-1)
057:
058: return img
059:
060: if __name__ == ‘__main__’:
061: print(cv2.__version__)
062:
063: __main()