Jump to content
Compvision.ru
Sigmoid

Вывод информации над рамкой

Recommended Posts

помогите пожалуйста с выводом информации над контуром рамки, как отобразить размер рамки, если известно что размер товара 670 пикселей, длина физ 4,1 мм, и как провести центр оси на объект? opencv версии 4.7.0.68, отредактируйте код.

 

спросил Cегодня
Изменено сегодня
Просмотрено 15 раз
-1

помогите пожалуйста с выводом информации над контуром рамки, как отобразить размер рамки, если известно что размер товара 670 пикселей, длина физ 4,1 мм, и как провести центр оси на объект? opencv версии 4.7.0.68, отредактируйте код.

import numpy as np

import cv2

cap = cv2.VideoCapture ( 1 )

kernel = np.ones ( (2 , 2) , np.uint8 )

while (True):

    # Capture frame-by-frame

    ret , frame = cap.read ()

    # Our operations on the frame come here

    gray = cv2.cvtColor ( frame , cv2.COLOR_BGR2GRAY )

    gray = cv2.GaussianBlur ( gray , (7 , 7) , 0 )

    gray = cv2.medianBlur ( gray , 5 )  # to remove salt and paper noise

    # to binary

    ret , thresh = cv2.threshold ( gray , 128 , 128 , 128 )  # to detect white objects

    # to get outer boundery only

    thresh = cv2.morphologyEx ( thresh , cv2.MORPH_GRADIENT , kernel )

    # to strength week pixels

    thresh = cv2.dilate ( thresh , kernel , iterations = 1 )

    im2 = contours , hierarchy = cv2.findContours ( thresh , cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE )

    if len ( contours ) > 0:

        cv2.drawContours ( frame , contours , -1 , (0 , 255 , 0) , 3 )

        # find the biggest countour (c) by the area

        c = max ( contours , key = cv2.contourArea )

        x , y , w , h = cv2.boundingRect ( c )

        # draw the biggest contour (c) in green

        cv2.rectangle ( frame , (x , y) , (x + w , y + h) , (255 , 0 , 0) , 2 )

    # Display the resulting frame

    cv2.imshow ( 'frame' , frame )

    if cv2.waitKey ( 27 ) & 0xFF == ord ( 'q' ):

        break

# When everything done, release the capture

cap.release ()

cv2.destroyAllWindows ()

IMG_20230121_114526.jpg

Share this post


Link to post
Share on other sites

Я не уверен понял пробблему, проблема с выводом текста в заданные координаты?

https://www.geeksforgeeks.org/python-opencv-cv2-puttext-method/

 

Share this post


Link to post
Share on other sites

Есть информация когда печатаю 

print(frameWidth) - в консоли выводит сообщение ширины "640", 

Так вот эту информацию 640 нужно вывести непосредственно над синей рамкой контура, 

 

И ещё я не знаю как найти центроид в контуре в виде линии которая будет рисовать ось.

 

Буду рад любой информации

 

 

 

Share this post


Link to post
Share on other sites

Так в программе, которую Вы приводите выше, координаты прямоугольника, ограничивающего контур, x,y - это верзнй левый угол, w, h - ширина и вытота.

Центр - x+w/2, y+h/2

Как выводить текст, см. пример по ссылке в моем предыдущем ответе.

Русские буквы стандартный cv2.outText не выведет, используйте латиницу.

  • Thanks 1

Share this post


Link to post
Share on other sites

Получилось, но при повороте объекта центр фрейма слетает с центра объекта(

Как можно нарисовать контур именно в центре объекта ?63ced12517800_PhotoCollageMaker_2023_01_23_09_16_58.thumb.jpg.f6282242bed581693607af14085912bf.jpg

В силу моего незнания - долго искал выход найти середину фрейма, вроде получилось с помощью 

 

 

cv2.rectangle (frame,(x,y),(x+w*1,y+h//2),(255,255,0),2)

Share this post


Link to post
Share on other sites

Ищите  собственные оси и центр масс.
Тут пример: https://robospace.wordpress.com/2013/10/09/object-orientation-principal-component-analysis-opencv/

  • Thanks 1

Share this post


Link to post
Share on other sites

Посмотрите еще:  cv.minAreaRect

собственные оси и этот метод рабртают немного по раному, смотрите сами какой больше подходит.

Описание здесь: https://docs.opencv.org/3.4/dd/d49/tutorial_py_contour_features.html

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

×