区分图像

时间:2018-01-05 12:58:25

标签: python opencv computer-vision

我的问题是我想区分下图中的亮区和暗区以生成二元遮罩。

https://i.stack.imgur.com/7ZRKB.jpg

输出的近似值可以是:

https://i.stack.imgur.com/2UuJb.jpg

我尝试了很多东西,但结果仍然有些噪音,或者我丢失了很多数据,比如这张图片:

https://i.stack.imgur.com/hUyjY.png

我使用了opencv和numpy,高斯过滤器,打开,关闭等python ...... 有人有想法这样做吗?

提前致谢!

3 个答案:

答案 0 :(得分:0)

我首先使用pyrDown缩小图像的大小,然后使用CLAHE来均衡直方图。我使用了medianblur,因为这将创建补丁,然后使用开放3次。之后,这是一个简单的binary_inv阈值。如果要获取原始图像大小,请在图像上使用cv2.pyrUp。通过使用参数,您可以设法获得更好的结果。

import cv2

image = cv2.imread("7ZRKB.jpg",0)
image = cv2.pyrDown(image)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(16,16))
image = clahe.apply(image)

image = cv2.medianBlur(image, 7)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=3)

ret,image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("image",image)

cv2.waitKey()
cv2.destroyAllWindows()

结果: enter image description here

答案 1 :(得分:-1)

代码,对不起!

image = cv2.imread(IMAGE_PATH, 0)
image = cv2.equalizeHist(image)
kernel = np.ones((5, 5),np.uint8)
image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=2)
image = cv2.dilate(image,kernel,iterations = 1)

image = cv2.GaussianBlur(image, (13, 13), 3)

ret,thresh1 = cv2.threshold(image, 100, 255, cv2.THRESH_BINARY)

cv2.imwrite(SAVE_PATH, thresh1)

答案 2 :(得分:-1)

image = cv2.imread(IMAGE)

#Change to HSV:
cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
image_blur = cv2.medianBlur(image,9)

#Split in 64 tiles:
NUM_TILES_H = image.shape[1]/ SIZE_TILES
NUM_TILES_V = image.shape[0]/ SIZE_TILES

#Prepare the final image
final_image = np.zeros_like(image)
for i in range(NUM_TILES_H):
    for k in range(NUM_TILES_V):
        window = image_blur[SIZE_TILES*k:SIZE_TILES*(k+1),SIZE_TILES*i:SIZE_TILES*(i+1),:]
        #window_b = cv2.medianBlur(window,7)
        #cv2.imwrite(os.path.join(SAVE,'w_'+str(i)+'_'+str(k)+'.jpg'), window)
        median_v = np.median(window[:,:,2])
        median_s = np.median(window[:,:,1])
        final = np.zeros_like(window)
        final[(window[:,:,2] > median_v + THRES) ]= [1,1,1]
        final_image[SIZE_TILES*k:SIZE_TILES*(k+1),SIZE_TILES*i:SIZE_TILES*(i+1),:] = final


#Fix the final image
kernel = np.ones((3,3), np.uint8)

final_image = cv2.morphologyEx(final_image,cv2.MORPH_OPEN,kernel,iterations=12)

final_image = cv2.morphologyEx(final_image, cv2.MORPH_CLOSE, kernel, iterations=8)

final_image = cv2.medianBlur(final_image,9)
cv2.imwrite(os.path.join(SAVE,'mask.png'), final_image[:,:,0]*255)
masked_image = np.copy(image)
masked_image[final_image[:,:,0] == 0] = 0
cv2.imwrite(os.path.join(SAVE,'masked_image.jpg'), masked_image)