I have a code in python that manualy selects a square to measure the CE symbol of a label. I would like to write a code that detects the "CE" symbol and measures its height and whidth. I would apreciate any help. The background in white anf the "CE" symbol is black but there re some other small black symbols near the "CE". Maybe I can give a "CE" template?
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Function to select an object in the image using mouse clicks
def select_object(event, x, y, flags, params):
global ref_point, cropping
if event == cv2.EVENT_LBUTTONDOWN:
ref_point = [(x, y)]
cropping = True
elif event == cv2.EVENT_LBUTTONUP:
ref_point.append((x, y))
cropping = False
# Draw a rectangle around the selected object
cv2.rectangle(image, ref_point[0], ref_point[1], (0, 255, 0), 2)
cv2.imshow("Image", image)
# Load the image
image = cv2.imread("label.jpg")
# Make a copy of the original image
clone = image.copy()
# Initialize variables for object selection
ref_point = []
cropping = False
# Create a window to display the image and set the mouse callback function
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", select_object)
# Display the image
cv2.imshow("Image", image)
# Wait for the user to select the object
cv2.waitKey(0)
# Calculate the pixel-to-millimeter conversion factor (you should adjust this based on your image)
pixel_to_mm = 0.1 # Example: 1 pixel corresponds to 0.1 mm
# Crop and measure the selected object
if len(ref_point) == 2:
roi = clone[ref_point[0][1]:ref_point[1][1], ref_point[0][0]:ref_point[1][0]]
# Measure the dimensions of the object in millimeters
height_pixels, width_pixels, _ = roi.shape
height_mm = height_pixels * pixel_to_mm
width_mm = width_pixels * pixel_to_mm
print(f"Object dimensions - Height: {height_mm:.2f} mm, Width: {width_mm:.2f} mm")
# Display the cropped object
cv2.imshow("Cropped Object", roi)
cv2.waitKey(0)
# Clean up
cv2.destroyAllWindows()