본문 바로가기
  • You find inspiration to create your own path !
업무 자동화/python & CAD

web으로 물체의 사이즈를 측정 하는 기능

by ToolBOX01 2025. 9. 1.
반응형

▣ 유튜브 동영상

  • ArUco 마커를 이용한 객체 크기 측정: 컴퓨터 비전을 사용하여 실시간으로 객체의 크기를 자동으로 측정하는 방법을 제시합니다. 이 접근법은 ArUco 마커를 기준점으로 활용하여 카메라 거리 및 원근법 관련 문제를 해결하고, 카메라에 대한 객체의 상대적 위치에 관계없이 일관된 크기 측정을 보장합니다.
  • 구현 단계: 이 프로세스는 픽셀 영역을 분석하여 객체를 감지한 다음, 알려진 물리적 크기의 ArUco 마커를 사용하여 픽셀 대 센티미터 비율을 설정합니다. 이 비율을 감지된 객체의 치수(가로 및 세로 픽셀)에 적용하여 실제 크기를 계산하며, 여러 객체를 동시에 처리할 수 있습니다.
  • 실시간 적용 및 보정: 이 기술은 카메라에서 프레임을 캡처하고 ArUco 마커를 감지하며 객체 크기를 동적으로 계산하여 실시간 비디오 분석에 구현할 수 있습니다. 렌즈 왜곡으로 인해 약간의 부정확성이 발생할 수 있지만, 핵심 방법은 시각적 인식 프로젝트에 강력하고 간단한 솔루션을 제공합니다.

▶ 파이썬 코드

import cv2
import numpy as np

def realtime_measure_with_dims():
    # Initialize webcam
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return
    
    print("Instructions: Place an A4 paper (29.7 cm x 21 cm) and the target object in the webcam's view.")
    print("Press 'q' to exit.")
    
    while True:
        # Capture frame
        ret, frame = cap.read()
        if not ret:
            print("Error: Could not capture frame.")
            break
        
        # Convert to grayscale and apply Gaussian blur
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.GaussianBlur(gray, (5, 5), 0)
        
        # Edge detection
        edges = cv2.Canny(blur, 50, 150)
        
        # Find contours
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        # Sort contours by area (largest first)
        contours = sorted(contours, key=cv2.contourArea, reverse=True)
        
        if len(contours) >= 2:
            # Assume largest contour is A4 paper, second largest is target object
            ref_contour = contours[0]
            target_contour = contours[1]
            
            # Get bounding rectangles
            ref_x, ref_y, ref_w, ref_h = cv2.boundingRect(ref_contour)
            target_x, target_y, target_w, target_h = cv2.boundingRect(target_contour)
            
            # Known dimensions of A4 paper in cm
            ref_width_cm = 29.7  # A4 width
            ref_height_cm = 21.0  # A4 height
            
            # Calculate pixel-to-cm ratio
            pixel_to_cm_width = ref_width_cm / ref_w
            pixel_to_cm_height = ref_height_cm / ref_h
            pixel_to_cm = (pixel_to_cm_width + pixel_to_cm_height) / 2  # Average for robustness
            
            # Calculate target object dimensions in cm
            target_width_cm = target_w * pixel_to_cm
            target_height_cm = target_h * pixel_to_cm
            
            # Draw bounding rectangles
            cv2.rectangle(frame, (ref_x, ref_y), (ref_x + ref_w, ref_y + ref_h), (0, 255, 0), 2)
            cv2.rectangle(frame, (target_x, target_y), (target_x + target_w, target_y + target_h), (0, 0, 255), 2)
            
            # Display dimensions above rectangles (rounded to one decimal place)
            cv2.putText(frame, f"{ref_width_cm:.1f}x{ref_height_cm:.1f} cm", 
                        (ref_x, ref_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
            cv2.putText(frame, f"{target_width_cm:.1f}x{target_height_cm:.1f} cm", 
                        (target_x, target_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
            
            # Print dimensions to console for debugging
            print(f"Target object dimensions: {target_width_cm:.1f} cm x {target_height_cm:.1f} cm")
        
        # Display frame
        cv2.imshow("Live Feed", frame)
        
        # Break loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # Release resources
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    realtime_measure_with_dims()

파일 다운 로드

realtime_measure_with_dims.py
0.00MB

프로그램을 중단하려면 "q" 클릭하세요


▶ OpenCV 라이브러리 배우기

 

 


반응형