解決:適切な数字を指定する
画像にモザイクなどをかけるとき、適切な数字を指定できていなければ以下のようなエラーが出る。
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
     19
     20 img = cv2.imread("cat.jpg")
---> 21 mos = mosaic(img, (50, 50, 350, 150), 10)
     22
     23 cv2.imwrite("cat-mosaic.png", mos)
     14
     15     img2 = img.copy()
---> 16     img2[y1:y2, x1:x2] = i_mos
     17     return img2
     18 
ValueError: could not broadcast input array from shape (100,300,3) into shape (100,175,3)
| 
					 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  | 
						import matplotlib.pyplot as plt import cv2 from mosaic import mosaic as mosaic def mosaic(img, rect, size):     (x1, y1, x2, y2) = rect     w = x2 - x1     h = y2 - y1     i_rect = img[y1:y2, x1:x2]     i_small = cv2.resize(i_rect, (size, size))     i_mos = cv2.resize(i_small, (w, h), interpolation=cv2.INTER_AREA)     img2 = img.copy()     img2[y1:y2, x1:x2] = i_mos     return img2 img = cv2.imread("cat.jpg") mos = mosaic(img, (50, 50, 350, 150), 10) cv2.imwrite("cat-mosaic.png", mos) plt.imshow(cv2.cvtColor(mos, cv2.COLOR_BGR2RGB)) plt.show  | 
					
mos = mosaic(img, (50, 50, 350, 150), 10)の350を150にしてみるとエラーは発生しない。
これはあくまで例。その時々によって変更すべき箇所が変わる。
| 
					 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  | 
						import matplotlib.pyplot as plt import cv2 from mosaic import mosaic as mosaic def mosaic(img, rect, size):     (x1, y1, x2, y2) = rect     w = x2 - x1     h = y2 - y1     i_rect = img[y1:y2, x1:x2]     i_small = cv2.resize(i_rect, (size, size))     i_mos = cv2.resize(i_small, (w, h), interpolation=cv2.INTER_AREA)     img2 = img.copy()     img2[y1:y2, x1:x2] = i_mos     return img2 img = cv2.imread("cat.jpg") mos = mosaic(img, (50, 50, 150, 150), 10)  # 150へ変更 cv2.imwrite("cat-mosaic.png", mos) plt.imshow(cv2.cvtColor(mos, cv2.COLOR_BGR2RGB)) plt.show  | 
					
まとめ
画像を扱う際に、適切な数字を指定できているか確かめよう。
数字の大きさを大きくしたり小さくしたりしてみよう。