python处理缺陷图象返回缺陷面积数量

import cv2
import numpy as np
import os
global allmin
global allmax
global allarea
global allnum
allmin=50000
allmax=0
allarea=0
allnum=0
def Change(img):
# 改黑白图为白黑图，也可以用cvThreshold函数
sp = img.shape
height = sp[0]  # height(rows) of image
width = sp[1]  # width(colums) of image
size = (width, height)
iTmp = np.zeros(img.shape, np.uint8)
for i in range(height):
for j in range(width):
iTmp[i, j] = 255 - img[i, j]
cv2.imwrite(path, iTmp)# 覆盖原黑白图
print("图像 %s 覆盖成功！" % (path))

# 消除微小区域
def Big(contour):
c_max = []
for i in range(len(contour)):
cnt = contours[i]
area = cv2.contourArea(cnt)
if area < 30:
contour.append(contour[i])
c_min = []
c_min.append(cnt)
# thickness不为-1时，表示画轮廓线，thickness的值表示线的宽度。
cv2.drawContours(img, c_min, -1, (0, 0, 0), thickness=-1)
continue
c_max.append(cnt)
cv2.drawContours(img, c_max, -1, (255, 255, 255), thickness=-1)
cv2.imwrite(path, img)
print("图像 %s 修改成功！" % (path))

def areaCal(contour):
global allmin
global allmax
global allarea
global allnum
area = 0
min=111111
max=0

for i in range(len(contour)):
if cv2.contourArea(contour[i])>10:
if cv2.contourArea(contour[i])>max:
max=cv2.contourArea(contour[i])
if cv2.contourArea(contour[i])<min:
min=cv2.contourArea(contour[i])
area += cv2.contourArea(contour[i])
# print(len(contour))
print("共 %d 个区域，第 %d 个区域的面积为： %d" %(len(contour),i+1,cv2.contourArea(contour[i])))
if area == 0:
min = 0
if min < allmin and min > 0:
allmin = min
if max > allmax:
allmax = max
allarea +=area
allnum += len(contour)
print("区域总面积为：%d,最大面积为： %d，最小面积为： %d" % (area,max,min))
#计算缺陷周长
def perimeterCal(contour):

perimeter=0
for i in range(len(contour)):
if cv2.arcLength(contour[i],True)>10:
perimeter += cv2.arcLength(contour[i],True)
# print("共 %d 个缺陷，第 %d 个缺陷的周长为： %d" % (len(contour), i+1, cv2.arcLength(contour[i],True)))
print("区域总周长为：%d" % perimeter)

num=0
filenum = 0
print("程序开始运行......")
# if num==668:
while num<1600:
num += 1
path='E:/cvtest/'+ str(num) +'.bmp'
if os.path.exists(path):
filenum += 1
img = cv2.imread(path)
print("图像 %s 加载成功！" %(path))
# Change(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 轮廓检测函数
binary,contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
# Big(contours)

areaCal(contours)
perimeterCal(contours)
cv2.imshow("binary", binary)
cv2.imshow("outline", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

averagearea = allarea/allnum
averagenum = allnum/filenum
print("区域最大面积为：%d" % (allmax))
print("区域最小面积为：%d" % (allmin))
print("区域平均面积为：%d" % (averagearea))
print("区域平均数量为：%d" % (averagenum))
print("区域总数量为：%d" % (allnum))
print("图像总数量为：%d" % (filenum))



• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120