34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
import cv2
|
|
import sys
|
|
|
|
CASCADE_PATH = "src/face.xml"
|
|
|
|
|
|
def detect_and_draw(image_path: str, out_path: str | None = None):
|
|
img = cv2.imread(image_path)
|
|
if img is None:
|
|
print("Gagal membuka gambar:", image_path)
|
|
return []
|
|
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
|
face_cascade = cv2.CascadeClassifier(CASCADE_PATH)
|
|
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
|
print(f"Found {len(faces)} face(s)")
|
|
for (x, y, w, h) in faces:
|
|
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
|
if out_path:
|
|
cv2.imwrite(out_path, img)
|
|
print("Saved output to", out_path)
|
|
else:
|
|
cv2.imshow("Detections", img)
|
|
cv2.waitKey(0)
|
|
cv2.destroyAllWindows()
|
|
return faces
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python detect_cv.py path/to/image.jpg [out.jpg]")
|
|
else:
|
|
out = sys.argv[2] if len(sys.argv) > 2 else None
|
|
detect_and_draw(sys.argv[1], out)
|