1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import cv2 import numpy as np
def color(lower, upper, name): Img = cv2.imread('image/origin/all.png')
kernel_3 = np.ones((3, 3), np.uint8)
if Img is not None: HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV)
if name == 'red': mask = cv2.inRange(HSV, lower[:3], upper[:3]) mask = mask + cv2.inRange(HSV, lower[3:], upper[3:]) else: mask = cv2.inRange(HSV, lower, upper)
erosion = cv2.erode(mask, kernel_3, iterations=1) erosion = cv2.erode(erosion, kernel_3, iterations=1) dilation = cv2.dilate(erosion, kernel_3, iterations=1) dilation = cv2.dilate(dilation, kernel_3, iterations=1)
cv2.bitwise_and(Img, Img, mask=dilation)
ret, binary = cv2.threshold(dilation, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for index, contour in enumerate(contours): x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(Img, (x, y), (x + w, y + h), (0, 255,), 3) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(Img, name + str(index+1), (x - 10, y + 10), font, 1, (0, 0, 255), 2)
print(name, '方块的数量是', len(contours), '个')
cv2.namedWindow('Img', 0) cv2.imshow('Img', Img) cv2.imwrite('./image/' + name + '.png', Img)
while True: key = cv2.waitKey(10) & 0xFF if key == 27 or cv2.getWindowProperty('Img', cv2.WND_PROP_VISIBLE) < 1.0: break
if __name__ == '__main__': lower_yellow = np.array([20, 20, 20]) upper_yellow = np.array([30, 255, 255])
lower_red = np.array([0, 43, 46, 156, 43, 46]) higher_red = np.array([10, 255, 255, 180, 255, 255])
lower_green = np.array([35, 110, 106]) higher_green = np.array([77, 255, 255])
lower_blue = np.array([78, 43, 46]) upper_blue = np.array([110, 255, 255]) color(lower_blue, upper_blue, 'blue')
|