-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathflower_classify.py
58 lines (44 loc) · 1.64 KB
/
flower_classify.py
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
__author__ = 'XJH'
from rgbhistogram import RGBHistogram
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import numpy as np
import glob
import cv2
imagePaths = sorted(glob.glob("images/*.png"))
maskPaths = sorted(glob.glob("masks/*.png"))
data = []
target = []
desc = RGBHistogram([8, 8, 8])
for (imagePath, maskPath) in zip(imagePaths, maskPaths):
image = cv2.imread(imagePath)
mask = cv2.imread(maskPath)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
features = desc.describe(image, mask)
data.append(features)
target.append(imagePath.split("_")[-2])
targetNames = np.unique(target)
le = LabelEncoder()
target = le.fit_transform(target)
(trainData, testData, trainTarget, testTaeget) = train_test_split(data,
target,
test_size=0.3,
random_state=42)
model = RandomForestClassifier(n_estimators=25, random_state=84)
model.fit(trainData, trainTarget)
print(classification_report(testTaeget, model.predict(testData),
target_names=targetNames))
for i in np.random.choice(np.arange(0, len(imagePaths)), 10):
imagePath = imagePaths[i]
maskPath = maskPaths[i]
image = cv2.imread(imagePath)
mask = cv2.imread(maskPath)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
features = desc.describe(image, mask)
flower = le.inverse_transform(model.predict([features]))[0]
print(imagePath)
print("I think this flower is a {}".format(flower.upper()))
cv2.imshow("image", image)
cv2.waitKey(0)