如何解决如何用4像素扩展特定的颜色斑点?
我正在尝试将顶部布料分割扩展为4个像素。如何使用Opencv做到这一点?
下面是图像的灰度版本。
解决方法
签出
import numpy as np
import cv2
winname = 'clothes'
erode_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
dilate_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11))
# dilate_kernel size = (<desired expansion> + (<erode_kernel size> - 1) / 2) * 2 + 1
def on_mouse(event,x,y,flag,img):
if event == cv2.EVENT_LBUTTONUP:
# get only pixels of selected color with black background
color = img[y][x]
selection = np.where(img == color,img,0)
# split image and selection by channels as next code doesn't work
# with multichannel images
channels_img = cv2.split(img)
channels_sel = cv2.split(selection)
for i in range(len(channels_sel)):
# remove noise pixels of the same color
channels_sel[i] = cv2.erode(channels_sel[i],erode_kernel)
# now expand selected blob
# note that dilation kernel must compensate erosion so
# add erosion kernel size to it
channels_sel[i] = cv2.dilate(channels_sel[i],dilate_kernel)
# replace fragment on original image with expanded blob
mask = cv2.threshold(channels_sel[i],255,cv2.THRESH_BINARY_INV)[1]
channels_img[i] = cv2.bitwise_and(channels_img[i],mask)
channels_img[i] = cv2.bitwise_or(channels_img[i],channels_sel[i])
# merge processed channels back
img = cv2.merge(channels_img)
selection = cv2.merge(channels_sel)
cv2.imshow(winname,img)
cv2.imshow('selection',selection)
img = cv2.imread('images/clothes.png')
cv2.imshow(winname,img)
cv2.setMouseCallback(winname,on_mouse,img)
cv2.waitKey()
,
这是一种方法:
- 将图像加载为灰度
- 提取像素== 4
- 使用中值滤波器消除噪声
- 利用盘状结构元素对提取区域进行形态学扩张
- 通过将
4
放在膨胀像素所在的位置,并将原始图像放在其他位置来创建输出图像 - 保存
#!/usr/bin/env python3
import cv2
import numpy as np
# Load image
im = cv2.imread('clothes.png',cv2.IMREAD_GRAYSCALE)
# Extract top cloth,i.e. just class 4
topCloth = np.where(im==4,0).astype(np.uint8)
# Remove outlying noise pixels
topClothSmooth = cv2.medianBlur(topCloth,5)
# Create disk-shaped structuring element and dilate
SE = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
dilated = cv2.dilate(topClothSmooth,SE)
# Apply dilated class back to original image,so where dilated > 0,put 4,elsewhere put original
res = np.where(dilated>0,4,im)
# Save
cv2.imwrite('result.png',res)
结果如下:
以下是原始版本和结果之间的动画版本:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。