- contourArea因为以边缘像素中心为边长计算,所以面积会小于实际面积
- opencv python:https://docs.opencv.org/4.x/d3/d05/tutorial_py_table_of_contents_contours.html
- C++:https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0
import cv2
import numpy as np
im=cv2.imread("lwd.jpg")
h,w,c=im.shape
raw=np.zeros((h,w,c))
for line in open("lwd.txt"):
sp=line.split()
x = int(float(sp[1])*w)
y = int(float(sp[2])*h)
ww = int(float(sp[3])*w)
hh = int(float(sp[4])*h)
raw[y:y+hh, x:x+ww] = im[y:y+hh, x:x+ww]
raw=np.uint8(raw)
cv2.imshow("hh", raw)
cv2.waitKey()
mask = cv2.cvtColor(raw, cv2.COLOR_BGR2GRAY)
thresh, mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
image, contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
image = cv2.drawContours(im, contours,-1,(0,0,255),2)
for contour in contours:
print('*'*19)
print(len(contour))
print(cv2.contourArea(contour))
x,y,w,h = cv2.boundingRect(contour)
tmp = mask[y:y+h, x:x+w]
print(cv2.countNonZero(tmp))
tmp = raw[y:y+h, x:x+w]
cv2.imshow("hh", tmp)
cv2.waitKey()