气泡检测
import cv2
import os
import numpy as np
def bub_check(img_path, img_file, im, im_gray):
t, im_bin = cv2.threshold(im_gray,
170, 255,
cv2.THRESH_BINARY)
cv2.imshow("im_bin", im_bin)
img, cnts, hie = cv2.findContours(
im_bin,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE)
new_cnts = []
for cnt in cnts:
area = cv2.contourArea(cnt)
print("area:", area)
if area < 10000 and area > 22:
new_cnts.append(cnt)
im_cnt = cv2.drawContours(im,
new_cnts,
-1,
(0, 0, 255), 2)
cv2.imshow("im_cnt", im_cnt)
if len(new_cnts) > 0:
print("气泡瑕疵:", img_path)
def balance_check(img_path, img_file, im, im_gray):
im_blur = cv2.GaussianBlur(im_gray, (5, 5), 0)
kernel = np.ones((5, 5), np.uint8)
im_dilate = cv2.dilate(im_blur, kernel)
cv2.imshow("im_dilate", im_dilate)
im_canny = cv2.Canny(im_dilate, 60, 200)
cv2.imshow("im_canny", im_canny)
img, cnts, hie = cv2.findContours(
im_canny,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE)
new_cnts = []
if len(cnts) > 0:
for c in cnts:
circle_len = cv2.arcLength(c,
True)
if circle_len >= 1000:
new_cnts.append(c)
new_cnts = sorted(new_cnts,
key=cv2.contourArea,
reverse=True)
new_cnts = new_cnts[1:2]
im_cnt = cv2.drawContours(im,
new_cnts,
-1,
(0, 0, 255), 2)
cv2.imshow("im_cnt", im_cnt)
max_x = new_cnts[0][0][0][0]
max_y = new_cnts[0][0][0][1]
min_x = max_x
min_y = max_y
for cnt in new_cnts[0]:
if cnt[0][0] >= max_x:
max_x = cnt[0][0]
if cnt[0][0] <= min_x:
min_x = cnt[0][0]
if cnt[0][1] >= max_y:
max_y = cnt[0][1]
if cnt[0][1] <= min_y:
min_y = cnt[0][1]
center_y = int((max_y + min_y) / 2)
center_up = int((center_y + min_y) / 2)
center_down = int((center_y + max_y) / 2)
cv2.line(im, (min_x, center_up), (max_x, center_up),
(0, 0, 255), 2)
cv2.line(im, (min_x, center_down), (max_x, center_down),
(0, 0, 255), 2)
cv2.imshow("im_line", im)
cross_point_up = set()
cross_point_down = set()
for cnt in new_cnts[0]:
x, y = cnt[0][0], cnt[0][1]
if y == center_up:
cross_point_up.add((x, y))
if y == center_down:
cross_point_down.add((x, y))
cross_point_up = list(cross_point_up)
cross_point_down = list(cross_point_down)
for p in cross_point_up:
cv2.circle(im,
(p[0], p[1]), 8,
(0, 0, 255), 2)
for p in cross_point_down:
cv2.circle(im,
(p[0], p[1]), 8,
(0, 0, 255), 2)
cv2.imshow("im_circle", im)
len_up, len_down = 0, 0
p1 = cross_point_up[0]
p2 = cross_point_up[1]
len_up = abs(p1[0] - p2[0])
p3 = cross_point_down[0]
p4 = cross_point_down[1]
len_down = abs(p3[0] - p4[0])
print("len_up:", len_up)
print("len_down:", len_down)
if abs(len_up - len_down) >= 10:
print("大小头:", img_path)
else:
print("正常大小")
if __name__ == "__main__":
img_dir = "capsules"
img_files = os.listdir(img_dir)
for img_file in img_files:
img_path = os.path.join(img_dir, img_file)
if os.path.isdir(img_path):
continue
im = cv2.imread(img_path)
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow("im", im)
cv2.imshow("im_gray", im_gray)
balance_check(img_path, img_file, im, im_gray)
cv2.waitKey()
cv2.destroyAllWindows()