图像分割-欧式距离

问题:请完整地将图中的小丑鱼分割出来(包括橙色,白色和黑色区域),分割后请用其它颜色做背景色。

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()

 结果图:

 可以看到,使用欧式距离法可以大致将鱼从原图中分离出来,并将背景替换为蓝色背景,效果还不错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

F0reverBound

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值