# 共通パス
base_path = '/content/drive/My Drive/Colab Notebooks/'
# パスの設定
config_path = base_path + 'yolov4-tiny.cfg'
weights_path = base_path + 'yolov4-tiny.weights'
labels_path = base_path + 'coco.names'
image_path = base_path + 'car_4.jpg'
def load_labels(path):
with open(path, 'r') as f:
return [line.strip() for line in f.readlines()]
def load_network(config_path, weights_path):
return cv2.dnn.readNetFromDarknet(config_path, weights_path)
def get_output_layers(net):
layer_names = net.getLayerNames()
return [layer_names[i - 1] for i in net.getUnconnectedOutLayers().flatten()]
def detect_objects(net, image, output_layers):
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
return net.forward(output_layers)
def draw_predictions(image, detections, labels):
H, W = image.shape[:2]
boxes =
confidences =
class_ids =
detected_labels =
for detection in detections:
for output in detection:
scores = output[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
box = output[:4] * np.array([W, H, W, H])
centerX, centerY, width, height = box.astype('int')
x, y = int(centerX - width / 2), int(centerY - height / 2)
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold=0.5, nms_threshold=0.4)
if len(indices) > 0:
for i in indices.flatten():
x, y, w, h = boxes[i]
color = [int(c) for c in np.random.randint(0, 255, size=(3,))]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = "{}: {:.4f}".format(labels[class_ids[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
detected_labels.append(labels[class_ids[i]])
return Counter(detected_labels)
# 実行部分
labels = load_labels(labels_path)
net = load_network(config_path, weights_path)
output_layers = get_output_layers(net)
image = cv2.imread(image_path)
detections = detect_objects(net, image, output_layers)
label_counts = draw_predictions(image, detections, labels)
for label, count in label_counts.items():
print(f"{label}: {count}")
cv2_imshow(image)