import cv2
import numpy as np
import time
from PIL import Image, ImageDraw
if __name__ == '__main__':
im = cv2.imread('grass.jpg')
size=(600,400)
w,h=size
print(w,h)
Img = cv2.resize(im, size)
img=Image.open('grass.jpg').convert('RGBA').resize((600,400))
kernel_2 = np.ones((2,2),np.uint8)
kernel_3 = np.ones((3,3),np.uint8)
kernel_4 = np.ones((4,4),np.uint8)
if Img is not None:
HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV)
'''
HSV模型中颜色的参数分别是:色调(H),饱和度(S),明度(V)
下面两个值是要识别的颜色范围
'''
Lower = np.array([35, 43, 35])
Upper = np.array([90, 255, 255])
mask = cv2.inRange(HSV, Lower, Upper)
erosion = cv2.erode(mask,kernel_4,iterations = 1)
erosion = cv2.erode(erosion,kernel_4,iterations = 1)
dilation = cv2.dilate(erosion,kernel_4,iterations = 1)
dilation = cv2.dilate(dilation,kernel_4,iterations = 1)
target = 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)
p=0
cowimg=Image.open('cow.png').convert('RGBA')
cowsize=cowimg.size
cowimg=cowimg.resize((int(w*0.07),int(h*0.07)))
box=cowimg.crop((0,0,w*0.07,h*0.07))
box = cowimg.crop()
print(cowsize,box)
for i in contours:
x,y,w,h = cv2.boundingRect(i)
cv2.rectangle(Img,(x,y),(x+w,y+h),(0,255,),3)
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(Img,str(p),(x-10,y+10), font, 1,(0,0,255),2)
location = (int(x+w*0.5),int(y+h*0.5))
img.paste(box,location)
p +=1
print ('绿色方块的数量是',p,'个')
cv2.imshow('img', Img)
img.show()
cv2.imwrite('img.png', Img)
while True:
Key = chr(cv2.waitKey(15) & 255)
if Key == 'q':
cv2.destroyAllWindows()
break