简体   繁体   English

如何对特定区域进行直方图均衡

[英]How to do Histogram Equalization on specific area

I have a image and I want to do HE or CLAHE on specific area of the image.我有一张图片,我想在图片的特定区域做 HE 或 CLAHE。 I already have a mask for the image.我已经有了图像的蒙版。 Is there any possible way to do so?有什么可能的方法吗?

To do so you need to perform the operation on the pixel intensities of the image which fall within the mask.为此,您需要对落在掩码内的图像的像素强度执行操作。 For that these intensities must be stored separately.为此,这些强度必须单独存储。

Procedure:程序:

  • Get the pixel locations of those in white (255), within the mask.获取蒙版内白色 (255) 的像素位置。
  • Pick intensity values (0 - 255) from the gray image present in these locations.从这些位置的灰度图像中挑选强度值 (0 - 255)。
  • Perform your operation (CLAHE or HE) on these intensities.对这些强度执行您的操作(CLAHE 或 HE)。 The result is a different collection of intensities.结果是强度的不同集合。
  • Place these new intensity values in the collected locations.将这些新的强度值放在收集的位置。

Sample:样本:

Input image:输入图像:

在此处输入图像描述

Mask image:蒙版图片:

在此处输入图像描述

Code:代码:

import cv2
import numpy as np

# read sample image, convert to grayscale
img = cv2.imread('flower.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# read mask image as binary image
mask = cv2.imread('flower_mask.jpg', 0)

# Step 1: store locations with value 255 (white)
loc = np.where(mask == 255)

# Step 2: Pick intensity values in these locations from the grayscale image:
values = gray[loc]

# Step 3: Histogram equalization on these values:
enhanced_values = cv2.equalizeHist(values)

# Step 4: Store these enhanced values in those locations:
gray2 = gray_img.copy()
for i, coord in enumerate(zip(loc[0], loc[1])):
    gray2[coord[0], coord[1]] = enhanced_values[i][0]

cv2.imshow('Enhanced image', gray2)

Enhance image:增强图像:

在此处输入图像描述

Grayscale image:灰度图像:

在此处输入图像描述

您可以简单地裁剪要在其上应用 CLAHE 的区域,然后处理裁剪后的图像

Here is the code to achieve that :这是实现这一目标的代码:

import cv2 as cv
import numpy as np

# Load your color  image
#src = cv.imread("___YourImagePath__.jpg", 
#cv.IMREAD_COLOR)

#Create random color image
src = np.random.randint(255, size=(800,800,3),dtype=np.uint8)
cv.imshow('Random Color Image',src)
cv.waitKey(0)


# conver to gray
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)

# process gray image
equalized = cv.equalizeHist(gray)

# create a mask (binary image with same size as source image )
height,width,depth = src.shape
mask = np.zeros((height,width))
cv.circle(mask,( int(width/2),int(height/2)),int(width/3),1,thickness=-1)


# display mask
cv.imshow('Mask',mask)
cv.waitKey(0)

# Copy processed region using the mask
ProcessedRegion = np.where(mask!=0,equalized,gray)

#display result
cv.imshow('Processed region result', ProcessedRegion)
cv.waitKey(0)

Output :输出 :

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM