2-1Gray.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: img = createImage()
005: cv2.imshow(‘Orignal’, img)
006:
007: # ここで処理を実行する
008: img = getGray(img)
009:
010: cv2.imshow(‘Final result’, img)
011: cv2.waitKey(0)
012:
013: cv2.destroyAllWindows()
014:
015: def getGray(img):
016: “””CPUを使用”””
017: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # グレースケールに変換する
018:
019: return img
020:
021: def createImage(): # 画像処理用のデータを生成
022: width = 600
023: height = 480
024:
025: size = (height, width, 3) # 縦480ピクセル 横640ピクセル 3チャンネル
026: img = np.zeros(size, dtype=np.uint8)
027: rete = 255 / width
028: for h in range(0, height):
029: for w in range(0, width):
030: data = int(w * rete)
031: img[h, w] = [data, data, data]
032: red = np.array([0., 0., 255.])
033: green = np.array([0., 255., 0.])
034: blue = np.array([255., 0., 0.])
035:
036: cyan = np.array([255., 255., 0.])
037: magenta = np.array([255., 0., 255])
038: yellow = np.array([0., 255., 255.])
039:
040: cv2.rectangle(img=img, pt1=(0, 0), pt2=(200, 200), color=red, thickness=-1)
041: cv2.rectangle(img=img, pt1=(200, 0), pt2=(400, 200), color=green, thickness=-1)
042: cv2.rectangle(img=img, pt1=(400, 0), pt2=(600, 200), color=blue, thickness=-1)
043:
044: cv2.rectangle(img=img, pt1=(0, 200), pt2=(200, 400), color=cyan, thickness=-1)
045: cv2.rectangle(img=img, pt1=(200, 200), pt2=(400, 400), color=magenta, thickness=-1)
046: cv2.rectangle(img=img, pt1=(400, 200), pt2=(600, 400), color=yellow, thickness=-1)
047:
048: return img
049:
050: if __name__ == ‘__main__’:
051: print(cv2.__version__)
052:
053: __main()