Skip to content

Instantly share code, notes, and snippets.

@AMiller42
Created September 3, 2021 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AMiller42/a9c625ae7f5f5e46081db9d73fdd00c2 to your computer and use it in GitHub Desktop.
Save AMiller42/a9c625ae7f5f5e46081db9d73fdd00c2 to your computer and use it in GitHub Desktop.
"""
Make a program that takes an image and classifies it as either "a goat" or "not a goat"
"""
# load the image and convert it to grayscale
image = cv2.imread("images/goat.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# initialize the list of class labels and the image
CLASSES = ["background", "aeroplane", "bicycle", "bird",
"boat", "bottle", "bus", "car",
"cat", "chair", "cow",
"diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train",
"tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
# define the model parameters
model = cv2.dnn.readNetFromCaffe("models/goat.prototxt", "models/goat.caffemodel")
# create the blob with the image
blob = cv2.dnn.blobFromImage(image, 0.007843, (W, H), 127.5)
# run the model
model.setInput(blob)
detections = model.forward()
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated with
# the prediction
confidence = detections[0, 0, i, 2]
# filter out weak detections by ensuring the `confidence` is
# greater than the minimum confidence
if confidence > args["confidence"]:
# extract the index of the class label from the `detections`,
# then compute the (x, y)-coordinates of the bounding box for
# the object
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
(startX, startY, endX, endY) = box.astype("int")
# display the prediction
label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
print("[INFO] {}".format(label))
cv2.rectangle(image, (startX, startY), (endX, endY),
COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
# show the output image
cv2.imshow("Output", image)
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment