问题:请完整地将图中的小丑鱼分割出来(包括橙色,白色和黑色区域),分割后请用其它颜色做背景色。
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = 'fish.jpg'
f_bgr = cv2.imread(img, cv2.IMREAD_COLOR)
f_rgb = cv2.cvtColor(f_bgr, cv2.COLOR_BGR2RGB)
bndbox = {'xmin': 170,
'ymin': 50,
'xmax': 610,
'ymax': 260}
f_rec = cv2.rectangle(f_rgb.copy(),
(bndbox['xmin'], bndbox['ymin']),
(bndbox['xmax'], bndbox['ymax']),
color=(255, 255, 0), thickness=5)
plt.imshow(f_rec)
plt.show()
def Euclid(f, box, d0):
H, W, C = f.shape
a = np.zeros(C, dtype='float')
b = np.zeros((H, W), dtype='int')
for c in range(C):
a[c] = np.mean(f[box[0]:box[2], box[1]:box[3], c])
a = a.reshape(C, 1)
for w in range(W):
for h in range(H):
if box[0] < w < box[2] and box[1] < h < box[3]:
z = f[h, w, :].reshape(C, 1)
d = z - a
DE = np.dot(d.T, d)
if DE.sum() >= d0:
b[h, w] = 1
else:
pass
return b
def Binary_padding(f, b):
g = f.copy()
H, W, C = g.shape
for h in range(H):
for w in range(W):
if b[h][w] == 0:
g[h, w, :] = [0, 0, 255] # 填充为蓝色
else:
pass
return g
# Euclid distance
D0_0 = 21000
g_u_b_0 = Euclid(f_rgb, list(bndbox.values()), d0=D0_0)
img_0 = Binary_padding(f_rgb, g_u_b_0)
img_0 = cv2.cvtColor(img_0, cv2.COLOR_RGB2BGR)
cv2.imshow('image', img_0)
cv2.imwrite('result.png', img_0)
cv2.waitKey()
cv2.destroyAllWindows()
结果图:
可以看到,使用欧式距离法可以大致将鱼从原图中分离出来,并将背景替换为蓝色背景,效果还不错。