切割后的灰度图
切割后的原图
转成二值图代码如下
点击查看代码
# This is a sample Python script.
import cv2
import numpy as np
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def masks_to_mask( masks):
'''
16位mask转8位二值mask
'''
# 注意: Sobel函数求完导数后会有负值,还有会大于255的值。而原图像是uint8,即8位无符号数,所以Sobel建立的图像位数不够,会有截断。
# 第二个参数可以传cv.CV_32F。在经过处理后,要用convertScaleAbs()函数将其转回原来的uint8形式。否则将无法显示图像,
# 而只是一副灰色的窗口。
x = cv2.Sobel(masks, cv2.CV_16S, 1, 0)
y = cv2.Sobel(masks, cv2.CV_16S, 0, 1)
absX = cv2.convertScaleAbs(x) # 转回uint8
absY = cv2.convertScaleAbs(y)
# 函数convertScaleAbs依次执行三个操作:缩放,获取绝对值,转换为无符号的8位类型
edge = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
# cv2.imshow("edge",edge)
edge1=edge
# num1=cv2.countNonZero(edge)
ret, edge1 = cv2.threshold(edge, 0, 255, cv2.THRESH_BINARY)
cv2.bitwise_not(edge1, edge1)
cv2.imshow("edge1", edge1)
cv2.imwrite('ConvertToBinary/dest/edge1.png', edge1)
mask = np.where(masks > 0, 255, 0)
mask = mask.astype(np.uint8)
cv2.bitwise_and(edge1, mask, mask)
cv2.imshow("result",mask)
return mask
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# print_hi('PyCharm')
src=cv2.imread('ConvertToBinary/src/003.png')
mask=masks_to_mask(src)
cv2.imwrite('ConvertToBinary/dest/result.png',mask)
# cv2.imshow("mask",mask)
cv2.waitKey(0)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
相当于生成一个黑色边缘的mask与原二值图做与与运算这样就可以生成多个临近物体分开的二值图
最后结果为
如果用普通方法转成的二值图为
请注意右下角白色部分| | | |
| ---- | ---- | ---- |
| | | |