在处理不规则形状的关键尺寸(宽度和高度)时,我遇到了一个小问题。 给定输入图像:
请考虑以下情况:BLOB的形状像向内弯曲,因此要测量其宽度,传统的minBounding Rectangle方法无法达到最佳效果。
我尝试了用矩形定界并从框中使用tl,tr,bl,br(左上,右上,左下,右下)点并将其用作中点计算参数的方法。然后通过它们画线。但这对于向内弯曲的图像来说是失败的。
以下是我使用Boundingbox查找宽度和高度的传统实现方式:
import cv2
import numpy as np
from imutils import perspective
from imutils import contours
import imutils
from scipy.spatial import distance as dist
import argparse
parser = argparse.ArgumentParser(description='Measuring critical dimensions through midpoint(centroid)')
parser.add_argument('--image', help='Path to image file.')
args = parser.parse_args()
font=cv2.FONT_HERSHEY_SIMPLEX
def midpoint(pta,ptb):
return((pta[0]+ptb[0])*0.5,(pta[1]+ptb[1])*0.5)
im_in = cv2.imread(args.image, 0)
_, thres2=cv2.threshold(im_in, 170, 255,cv2.THRESH_BINARY)
dilate = cv2.dilate(thres2,None)
erode = cv2.erode(dilate,None)
im_3=erode.copy()
blur=cv2.medianBlur(im_3,5)
_,contour2,_=cv2.findContours(blur,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)
for c in contour2:
area=cv2.contourArea(c)
if area >1000 and area <30000:
print(area)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.array(box,dtype="int")
(tl,tr,br,bl)=box
(tltrX,tltrY)=midpoint(tl,tr)
(blbrX,blbrY)=midpoint(bl,br)
(tlblX,tlblY)=midpoint(tl,bl)
(trbrX,trbrY)=midpoint(tr,br)
dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
dA = round(dA,3)
dB = round(dB,3)
cv2.circle(blur,(int(tltrX),int(tltrY)),5,(255,255,255),1)
cv2.putText(blur, "({},{})".format(dA,dB), (int(tltrX - 50),int(tltrY - 10) - 0),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1)
cv2.circle(blur,(int(blbrX), int(blbrY)), 5, (255, 255, 255), 1)
cv2.circle(blur,(int(tlblX), int(tlblY)), 5, (255, 255, 255), 1)
cv2.circle(blur,(int(trbrX), int(trbrY)), 5, (255, 255, 255), 1)
cv2.line(blur,(int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),(255,255,255),2)
cv2.line(blur,(int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),(255,255,255),2)
print(dA)
print(dB)
cv2.imshow('4',blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
我希望输出是从中点开始的东西,我找到图像边界处的像素(并且线在图像边界处被剪切,我可以得到这些点的像素值)作为中点的线。(不使用边界框方法)