在图像 opencv python 上绘制线条和到它们的距离

drawing lines and distance to them on image opencv python

我遇到了这样一个问题:我无法在确定颜色的图像上画线,也无法找出到这个地方的距离。帮助制作如下图:

我的代码:

import cv2
import numpy as np
from PIL import ImageGrab



    while True:
        screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
        rgb_screen = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)

        lower = np.array([72, 160, 160])
        upper = np.array([112, 249, 249])


        mask = cv2.inRange(rgb_screen, lower, upper)
        output = cv2.bitwise_and(rgb_screen, rgb_screen, mask=mask)

        cv2.imshow('window', output)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

我没有你的原图,帮不上什么忙。但是你可以阅读我的代码,也许会有一个想法。对于距离,我不知道你的意思,所以我举了一个例子来说明如何获得左上角到左下角的距离。您可以根据您的需求申请其他积分或按比例申请。

import cv2
import numpy as np

img = cv2.imread('untitled.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, threshold = cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
im, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
area = sorted(contours, key=cv2.contourArea, reverse=True)
c = area[0]
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
print(box)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
extreme_left = tuple(c[c[:, :, 0].argmin()][0])
extreme_top = tuple(c[c[:, :, 1].argmin()][0])
x1 = box[1,0]
y1 = box[1,1]
x2 = box[0,0]
y2 = box[0,1]
distance = np.sqrt( (x1 - x2)**2 + (y1 - y2)**2 )
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Distance: '+str(distance),(1,300), font, 0.5,(255,255,255),2,cv2.LINE_AA)
cv2.circle(img, (x2,y2), 5, (255, 0, 0), -1)
cv2.circle(img, (x1,y1), 5, (255, 0, 0), -1)
cv2.imshow('image', img)