我有一副图像,除开前景,背景都是黑色的,但是我只想提取前景区域像素点的均值,请问有什么办法。
#!/user/bin/env python3
# -*- coding: utf-8 -*-
import cv2
# 深度学习-图像识别
def getContuors(img):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
# print(area)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (0, 0, 0), 1)
peri = cv2.arcLength(cnt, True) # 轮廓长度
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
objCor = len(approx)
# print(objCor)
x, y, w, h = cv2.boundingRect(approx)
if objCor == 3:
objectType = 'Tri'
elif objCor == 4:
aspRatio = w / float(h)
# print(aspRatio)
if aspRatio > 0.95 and aspRatio < 1.05:
objectType = 'ZFX'
else:
objectType = 'CFX'
elif objCor > 4:
objectType = 'YX'
else:
objectType = 'NONE'
cv2.rectangle(imgContour, (x, y), (x + w, y + h), (255, 0, 0), 1)
cv2.putText(imgContour, objectType, (x + (w // 2) - 10, y + (h // 5) - 10), cv2.FONT_HERSHEY_COMPLEX, 0.5,
(0, 0, 0), 2)
img = cv2.imread('ss.png')
imgsize = cv2.resize(img, (500, 400)) # 裁剪后
imgContour = imgsize.copy()
imgGRAY = cv2.cvtColor(imgsize, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGRAY, (7, 7), 1) # 模糊度
imgCann = cv2.Canny(imgBlur, 50, 50)
getContuors(imgCann)
if __name__ == '__main__':
cv2.imshow('windows', imgCann)
cv2.imshow('window', imgContour)
cv2.waitKey(0)
你的意思是背景是黑的,前景灰阶高于0?,那不是直接阈值分割一下,吧前景分割出来计算下前景面积,然后计算下总灰阶值除一下不就有了