写真にモザイクをかけよう
今回は写真にモザイクをかけてみましょう。
モザイクは一定の範囲ごとにピクセルの色を平均して、その範囲を平均値の色で塗りつぶします。
写真にモザイクをかけるプログラム
以下のプログラムは、10 x 10 のブロックごとに色の平均を出して、そのブロックを塗りつぶしています。
ブロックの範囲を変えることによって、モザイクの粗さを変えることができます。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94  | 
						### インポート import pygame from pygame.locals import * ### 定数 WIDTH  = 640        # 幅 HEIGHT = 400        # 高さ STEP   = 10         # モザイク範囲 ### モジュール初期化 pygame.init() ### 画面設定 surface = pygame.display.set_mode((WIDTH,HEIGHT)) ### 写真読み込み img = pygame.transform.rotozoom(pygame.image.load("photo.jpg").convert(), 0, 0.2) ### 画像サイズ保存 img_w = img.get_width() img_h = img.get_height() ### 写真のピクセルを直接編集 pixel = pygame.PixelArray(img) ### Y座標、X座標の色を取得 for y in range(0, img_h, STEP):     for x in range(0, img_w, STEP):         ### RGBAリスト         rgba = []         ### 縦幅モザイク範囲         for step_y in range(STEP):             if img_h <= (y+step_y):     # 縦幅確認                 break             ### 横幅モザイク範囲             for step_x in range(STEP):                 if img_w <= (x+step_x): # 横幅確認                     break                 ### カラー定数をRGBA形式に変換                 rgba.append(surface.unmap_rgb(pixel[x+step_x][y+step_y]))         ### モザイク範囲の値を積算         mosaic = [0,0,0]         for color in rgba:             mosaic[0] += color[0]   # 赤             mosaic[1] += color[1]   # 緑             mosaic[2] += color[2]   # 青         ### モザイク範囲の平均値を取得         rgb_r = int(mosaic[0]/(STEP**2))    # 赤         rgb_g = int(mosaic[1]/(STEP**2))    # 緑         rgb_b = int(mosaic[2]/(STEP**2))    # 青         ### 縦幅モザイク範囲         for step_y in range(STEP):             if img_h <= (y+step_y):     # 縦幅確認                 break             ### 横幅モザイク範囲             for step_x in range(STEP):                 if img_w <= (x+step_x): # 横幅確認                     break                 ### 色を書き換え                 pixel[x+step_x][y+step_y] = (rgb_r,rgb_g,rgb_b) ### オブジェクト削除 del pixel ### 写真表示 surface.blit(img, (int((WIDTH-img_w)/2),int((HEIGHT-img_h)/2))) ### 画面更新 pygame.display.update() ### 無限ループ while True:     ### イベント処理     for event in pygame.event.get():         if event.type == KEYDOWN and event.key == K_ESCAPE:             break     else:         continue     ### whileループ終了     break ### 終了処理 pygame.quit()  | 
					
プログラムを実行すると、以下の画像が表示されます。
