python
1import matplotlib.pyplot as plt 2from matplotlib.patches import Polygon 3import numpy as np 4import cv2 5from IPython.display import Image 6Image(filename='sample.jpg') 7 8img = cv2.imread("sample.jpg") 9 10hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 11 12lower_color = np.array([20, 80, 10]) 13upper_color = np.array([50, 255, 255]) 14 15mask = cv2.inRange(hsv, lower_color, upper_color) 16output = cv2.bitwise_and(hsv, hsv, mask=mask) 17 18cv2.imwrite("sample2.jpg", output) 19Image(filename='sample2.jpg') 20 21 22image_file = 'sample10.jpg' 23Image(filename=image_file) 24 25 26img = cv2.imread(image_file) 27 28hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 29 30red = cv2.inRange(hsv, np.array([145, 70, 0]), np.array([180, 255, 255])) 31yellow = cv2.inRange(hsv, np.array([10, 80, 0]), np.array([50, 255, 255])) 32blue = cv2.inRange(hsv, np.array([108, 121, 0]), np.array([120, 255, 255])) 33 34kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) 35 36bin_imgs = {'red': red, 'yellow': yellow, 'blue': blue} 37 38fig, axes_list = plt.subplots(3, 1, figsize=(10, 18)) 39 40for ax, (label, bin_imgs) in zip(axes_list.ravel(), bin_imgs.items()): 41 ax.axis('off') 42 ax.set_title(label) 43 ax.imshow(bin_imgs, cmap=plt.cm.gray) 44plt.show() 45 46fig, ax = plt.subplots(figsize=(12, 10)) 47ax.axis('off') 48ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) 49 50for label, bin_img in bin_imgs.items(): 51 _, contours, _ = cv2.findContours( 52 bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 53 contours = list(filter(lambda cnt: len(cnt) > 1, contours)) 54 count = len(contours) 55 56 print('color = {} conunt: {}'.format(label, count)) 57 58 for cnt in contours: 59 cnt = np.squeeze(cnt, axis=1) 60 ax.add_patch(Polygon(cnt, fill=None, lw=2., color=label)) 61plt.show() 62
Traceback (most recent call last): File "sotuken.py", line 50, in <module> for label, bin_img in bin_imgs.items(): AttributeError: 'numpy.ndarray' object has no attribute 'items'
エラーメッセージです。
どこを直せばよろしいでしょうか?
本文のソースとエラーが発生した実行時のソースが違っていませんでしょうか?
50行目の内容が本文ソースとエラーメッセージで異なっています。
Traceback (most recent call last):
File "sotuken.py", line 50, in <module>
for label, bin_img in bin_imgs.items():
AttributeError: 'numpy.ndarray' object has no attribute 'items'
すいません…
こっちでした。改めて宜しくお願いします。
なるほど。本文をそちらのメッセージに修正してくださいね。