opencv - 如何用 4 个像素扩展特定的颜色斑点?
解决方案
看看这个
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], 0, 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()
推荐阅读
- node.js - 部分文本搜索(查找)在我的快速应用程序上不起作用
- android - Android BLE 设备、位置权限和新的 Google Play 家庭政策
- azure-ad-domain-services - Azure ADDS 中的 SamAccountName
- ios - 将 iOS Hybrid App 从 UIWebView 迁移到 WKWebview
- javascript - 我的脚本无法通过跨度循环
- java - Gradle 包不存在
- excel - 如果单元格值不以 cioi、600t 和 htk4 开头,则删除所有行
- mysql - 使用带有列映射的 python 将 XML 文件加载到 MySQL 数据库
- python - 如何从python子进程中检索输出
- lucene - 如何使用 Hibernate-Search 索引和搜索 ENUM 类型