我运行以下代码来创建矩形轮廓:
<?php
if(isset($_GET['image']))
{
shell_exec("sudo led-image-viewer -C /var/www/html/led/".urldecode($_GET['image'])." --led-gpio-mapping=adafruit-hat --led-rows=64 --led-cols=64");
}
?>
我想找到矩形轮廓的中心线和中心点。请告知。
答案 0 :(得分:3)
由于已经有了边界框,因此可以使用cv2.moments()
查找中心坐标。这给了我们质心(即对象的中心(x,y)坐标)
M = cv2.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
中心点就是(cX, cY)
,您可以使用cv2.circle()
cv2.circle(image, (cX, cY), 5, (36, 255, 12), -1)
类似地,我们可以使用cv2.line()
或Numpy切片绘制中心线
cv2.line(image, (x + int(w/2), y), (x + int(w/2), y+h), (0, 0, 255), 3)
image[int(cY - h/2):int(cY+h/2), cX] = (0, 0, 255)
import imutils
import cv2
import numpy as np
# load the image, convert it to grayscale, blur it slightly, and threshold it
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
# threshold the image, then perform a series of erosions + dilations to remove any small regions of noise
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# Find the index of the largest contour
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
M = cv2.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.circle(image, (cX, cY), 5, (36, 255, 12), -1)
# To draw line you can use cv2.line or numpy slicing
cv2.line(image, (x + int(w/2), y), (x + int(w/2), y+h), (0, 0, 255), 3)
# image[int(cY - h/2):int(cY+h/2), cX] = (36, 255, 12)
# show the output image
cv2.imshow("Image", image)
cv2.imwrite("Image.png", image)
cv2.waitKey(0)
答案 1 :(得分:2)
由于您已经在上面的代码中使用(x, y, w, h)
了x,y,w,h = cv2.boundingRect(cnt)
了所需的轮廓,因此垂直中线的中心可以由(x+w//2, y+h//2)
给出,垂直线可以使用以下内容绘制代码:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
# center line
cv2.line(image, (x+w//2, y), (x+w//2, y+h), (0, 0, 255), 2)
# below circle to denote mid point of center line
center = (x+w//2, y+h//2)
radius = 2
cv2.circle(image, center, radius, (255, 255, 0), 2)
输出: