I start my model and get a mask prediction of the area I would like to crop.
JavaScript
x
13
13
1
img = cv2.imread('picture.jpg')
2
img = cv2.resize(img, (224, 224))
3
print(img.shape)
4
T = np.zeros((1, 224, 224, 3), dtype='float32')
5
T[0]=img
6
prediction = model.predict(T , verbose=1)
7
prediction = prediction[0, :, : , :]
8
plt.imshow(img)
9
plt.show()
10
print(prediction.shape)
11
plt.imshow(np.squeeze(prediction).astype(np.float32))
12
plt.show()
13
This code is the closest I have gotten to the desired image, the problem with this image that is provided is that it doesn’t crop out black background
JavaScript
1
4
1
result = prediction * img
2
plt.imshow((result/255).astype(np.float32))
3
plt.show()
4
My desired image should be like this
Advertisement
Answer
You could try this:
JavaScript
1
12
12
1
prediction = np.squeeze(prediction).astype(np.float32)
2
threshold = 0.5
3
xmin,ymin,xmax,ymax = (-1,-1,-1,-1)
4
for j in range(224):
5
for i in range(224):
6
if prediction[j,i] <= threshold: continue
7
xmin = i if xmin == -1 or xmin > i else xmin
8
xmax = i if xmax == -1 or xmax < i else xmax
9
ymin = j if ymin == -1 or ymin > j else ymin
10
ymax = j if ymax == -1 or ymax < j else ymax
11
cropImg = img[ymin:ymax,xmin:xmax]
12