Python cv2.equalizeHist() Examples

The following are 30 code examples of cv2.equalizeHist(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: histcomparison.py    From pedestrian-haar-based-detector with GNU General Public License v2.0 8 votes vote down vote up
def main():
	imagePath = "img.jpg"
	
	img = cv2.imread(imagePath)
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
	
	generate_histogram(gray)
	
	cv2.imwrite("before.jpg", gray)

	gray = cv2.equalizeHist(gray)
	
	generate_histogram(gray)
	
	cv2.imwrite("after.jpg",gray)
	
	return 0 
Example #2
Source File: lung_cancer_utils.py    From sql_python_deep_learning with MIT License 6 votes vote down vote up
def manipulate_images(sample_image):
    batch = []
    cnt = 0
    dx = 40
    ds = 512
    for i in range(0, sample_image.shape[0] - 3, 3):
        tmp = []
        for j in range(3):
            img = sample_image[i + j]
            img = 255.0 / np.amax(img) * img
            img = cv2.equalizeHist(img.astype(np.uint8))
            img = img[dx: ds - dx, dx: ds - dx]
            img = cv2.resize(img, (224, 224))
            tmp.append(img)

        batch.append(tmp)
    batch = np.array(batch, dtype=np.float32)
    return batch 
Example #3
Source File: head_pose_normalizer.py    From pytorch_mpiigaze with MIT License 6 votes vote down vote up
def _normalize_image(self, image: np.ndarray,
                         eye_or_face: FaceParts) -> None:
        camera_matrix_inv = np.linalg.inv(self.camera.camera_matrix)
        normalized_camera_matrix = self.normalized_camera.camera_matrix

        scale = self._get_scale_matrix(eye_or_face.distance)
        conversion_matrix = scale @ eye_or_face.normalizing_rot.as_matrix()

        projection_matrix = normalized_camera_matrix @ conversion_matrix @ camera_matrix_inv

        normalized_image = cv2.warpPerspective(
            image, projection_matrix,
            (self.normalized_camera.width, self.normalized_camera.height))

        if eye_or_face.name in {FacePartsName.REYE, FacePartsName.LEYE}:
            normalized_image = cv2.cvtColor(normalized_image,
                                            cv2.COLOR_BGR2GRAY)
            normalized_image = cv2.equalizeHist(normalized_image)
        eye_or_face.normalized_image = normalized_image 
Example #4
Source File: hist_equalization.py    From plantcv with MIT License 6 votes vote down vote up
def hist_equalization(gray_img):
    """Histogram equalization is a method to normalize the distribution of intensity values. If the image has low
       contrast it will make it easier to threshold.

    Inputs:
    gray_img    = Grayscale image data

    Returns:
    img_eh = normalized image

    :param gray_img: numpy.ndarray
    :return img_eh: numpy.ndarray
    """

    if len(np.shape(gray_img)) == 3:
        fatal_error("Input image must be gray")

    img_eh = cv2.equalizeHist(gray_img)
    params.device += 1
    if params.debug == 'print':
        print_image(img_eh, os.path.join(params.debug_outdir, str(params.device) + '_hist_equal_img.png'))
    elif params.debug == 'plot':
        plot_image(img_eh, cmap='gray')

    return img_eh 
Example #5
Source File: contrast.py    From imgaug with MIT License 6 votes vote down vote up
def _augment_batch_(self, batch, random_state, parents, hooks):
        if batch.images is None:
            return batch

        images = batch.images

        iadt.allow_only_uint8(images, augmenter=self)

        for i, image in enumerate(images):
            if image.size == 0:
                continue

            image_warped = [
                cv2.equalizeHist(_normalize_cv2_input_arr_(image[..., c]))
                for c in sm.xrange(image.shape[2])]
            image_warped = np.array(image_warped, dtype=image_warped[0].dtype)
            image_warped = image_warped.transpose((1, 2, 0))

            batch.images[i] = image_warped
        return batch 
Example #6
Source File: face_detection_utilities.py    From Real-Time-Facial-Expression-Recognition-with-DeepLearning with MIT License 6 votes vote down vote up
def getFaceCoordinates(image):
    cascade = cv2.CascadeClassifier(CASCADE_PATH)
    
    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.equalizeHist(img_gray)
    rects = cascade.detectMultiScale(
        img_gray,
        scaleFactor=1.1,
        minNeighbors=3,
        minSize=(48, 48)
        )

    # For now, we only deal with the case that we detect one face.
    if(len(rects) != 1) :
        return None
    
    face = rects[0]
    bounding_box = [face[0], face[1], face[0] + face[2], face[1] + face[3]]

    # return map((lambda x: x), bounding_box)
    return bounding_box 
Example #7
Source File: 03_hist_equalize.py    From Practical-Computer-Vision with MIT License 6 votes vote down vote up
def main():
    # read an image 
    img = cv2.imread('../figures/_DSC2126.jpg')
    img = cv2.resize(img, (600,400))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    
    # hist,bins = np.histogram(img[100:400, 100:400].flatten(),256,[0,256])
    # cdf = hist.cumsum()
    # cdf_normalized = cdf * hist.max()/ cdf.max()
    
    # # plot hist normalized 
    # plot_hist_cdf(cdf_normalized, img[100:400, 100:400])
        
    equ = cv2.equalizeHist(gray)
    
    # create a CLAHE object (Arguments are optional).
    clahe = cv2.createCLAHE()
    cl1 = clahe.apply(gray)
    
    plot_gray(gray, equ, cl1) 
Example #8
Source File: process.py    From BusinessCardReader with MIT License 6 votes vote down vote up
def getRegions(img):
    grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # grayImg = cv2.equalizeHist(np.copy(grayImg))
    edges = cv2.Canny(grayImg,100,200,apertureSize = 3) 
    if DEBUG:
        utils.display([('Canny Edge Detection', edges)])
    kernel = np.ones((3,3),np.uint8)
    edges = cv2.dilate(edges,kernel,iterations = 14)
    # edges = 255-edges
    # utils.display([('', edges)])
    contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    if DEBUG:
        utils.display([('Contours', edges)])
    # Only take contours of a certain size
    regions = []
    for contour in contours:
        imgH, imgW, _ = img.shape
        [x, y, w, h] = cv2.boundingRect(contour)
        if w < 50 or h < 50:
            pass
        elif w > .95*imgW or h > .95*imgH:
            pass
        else:
            regions.append((x, y, x+w, y+h))
    return regions 
Example #9
Source File: evaluation.py    From pedestrian-haar-based-detector with GNU General Public License v2.0 5 votes vote down vote up
def normalize_grayimage(image):
	image = cv2.equalizeHist(image)
	#cv2.imshow("Equalized img", image)
	
	return image 
Example #10
Source File: oriental-bittersweet.py    From ImageAnalysis with MIT License 5 votes vote down vote up
def my_equalize(channel, method='clahe'):
    #print channel.min(), channel.max()
    if method == 'simple':
        result = cv2.equalizeHist(channel)
    elif method == 'clahe':
        result = clahe.apply(channel)
    #print result.min(), result.max()
    return result 
Example #11
Source File: testHaarCascade.py    From optimeyes with MIT License 5 votes vote down vote up
def handleFrame(frame, allowDebugDisplay=True):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)
    faces = detect(gray,haarFaceCascade)
    if allowDebugDisplay:
        output = frame
        draw_rects(output,faces,(0,255,0)) #BGR format
        cv2.imshow(WINDOW_NAME, cv2.resize(output,(0,0), fx=2,fy=2,interpolation=cv2.INTER_NEAREST) ) 
Example #12
Source File: operations.py    From Smart-Surveillance-System-using-Raspberry-Pi with GNU General Public License v3.0 5 votes vote down vote up
def normalize_intensity(images):
    """ This method normalizes the size and pixel intensity of an image.

    Each image has their own distribution of intensity pixels in grayscale.
    This function normalizes these intensities such that the image uses
    all the range of grayscale values.
    """
    images_norm = []
    for image in images:
        is_color = len(image.shape) == 3
        if is_color:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        images_norm.append(cv2.equalizeHist(image))
    return images_norm 
Example #13
Source File: color_histogram_equalization_hsv.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def equalize_hist_color_hsv(img):
    """Equalizes the image splitting it after HSV conversion and applying cv2.equalizeHist()
    to the V channel, merging the channels and convert back to the BGR color space
    """

    H, S, V = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
    eq_V = cv2.equalizeHist(V)
    eq_image = cv2.cvtColor(cv2.merge([H, S, eq_V]), cv2.COLOR_HSV2BGR)
    return eq_image


# Create the dimensions of the figure and set title: 
Example #14
Source File: augmentor.py    From A-Light-and-Fast-Face-Detector-for-Edge-Devices with MIT License 5 votes vote down vote up
def histogram_equalisation(image):
        """
        do histogram equlisation for grayscale image
        :param image: input image with single channel 8bits
        :return: processed image
        """
        if image.ndim != 2:
            print('Input image is not grayscale!')
            return None
        if image.dtype != numpy.uint8:
            print('Input image is not uint8!')
            return None

        result = cv2.equalizeHist(image)
        return result 
Example #15
Source File: color_histogram_equalization.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def equalize_hist_color(img):
    """Equalize the image splitting the image applying cv2.equalizeHist() to each channel and merging the results"""

    channels = cv2.split(img)
    eq_channels = []
    for ch in channels:
        eq_channels.append(cv2.equalizeHist(ch))

    eq_image = cv2.merge(eq_channels)
    return eq_image


# Create the dimensions of the figure and set title: 
Example #16
Source File: rpotter.py    From rpotter with MIT License 5 votes vote down vote up
def FindNewPoints():
    global old_frame,old_gray,p0,mask,color,ig,img,frame
    try:
        try:
            old_frame = cam.capture(stream, format='jpeg')
        except:
            print("resetting points")
        data = np.fromstring(stream.getvalue(), dtype=np.uint8)
        old_frame = cv2.imdecode(data, 1)
        cv2.flip(old_frame,1,old_frame)
        old_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY)
        #cv2.equalizeHist(old_gray,old_gray)
	    #old_gray = cv2.GaussianBlur(old_gray,(9,9),1.5)
        #dilate_kernel = np.ones(dilation_params, np.uint8)
        #old_gray = cv2.dilate(old_gray, dilate_kernel, iterations=1)

        #TODO: trained image recognition
        p0 = cv2.HoughCircles(old_gray,cv2.HOUGH_GRADIENT,3,100,param1=100,param2=30,minRadius=4,maxRadius=15)
        p0.shape = (p0.shape[1], 1, p0.shape[2])
        p0 = p0[:,:,0:2]
        mask = np.zeros_like(old_frame)
        ig = [[0] for x in range(20)]
        print("finding...")
        TrackWand()
	    #This resets the scene every three seconds
        threading.Timer(3, FindNewPoints).start()
    except:
        e = sys.exc_info()[1]
        print("FindWand Error: %s" % e )
        End()
        exit 
Example #17
Source File: preprocess.py    From Brain-Segmentation with MIT License 5 votes vote down vote up
def histeq(data):
    for slice_index in range(data.shape[2]):
        data[:,:,slice_index]=cv.equalizeHist(data[:,:,slice_index])
    return data 
Example #18
Source File: facerec_train.py    From deepvisualminer with MIT License 5 votes vote down vote up
def recognize(img_file, expected_label, models_dir, eigen=True, fischer=True, lbp=True, equalize_hist=False):

    eigen_label = fischer_label = lbp_label = -1

    with open(os.path.join(models_dir, 'model.json'), 'r') as model_file:
        model = json.load(model_file)
        train_img_size = (model['height'], model['width'])
       
    img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
    # If training images were equalized, better to perform the same 
    # operation during recognition too.
    if equalize_hist:
        img = cv2.equalizeHist(img)
        
    if img.shape != train_img_size:
        img = cv2.resize( img, train_img_size[::-1] )
    
    if eigen:
        eigen_recog = face.createEigenFaceRecognizer();
        eigen_recog.load(os.path.join(models_dir, 'eigen.yml'))
        eigen_label = eigen_recog.predict(img)
        print('Eigen done')
    
    if fischer:
        fischer_recog = face.createFisherFaceRecognizer();
        fischer_recog.load(os.path.join(models_dir, 'fischer.yml'))
        fischer_label = fischer_recog.predict(img)
        print('Fischer done')
    
    if lbp:
        lbp_recog = face.createLBPHFaceRecognizer();
        lbp_recog.load(os.path.join(models_dir, 'lbp.yml'))
        lbp_label = lbp_recog.predict(img)
        print('LBP done')
    
    
    print(eigen_label, fischer_label, lbp_label)
    return  eigen_label, fischer_label, lbp_label 
Example #19
Source File: ColorAugmenters.py    From impy with Apache License 2.0 5 votes vote down vote up
def histogramEqualization(self, frame = None, equalizationType = None):
		"""
		Args:
			frame: A tensor that contains an image.
			equalizationType: An int that defines what type of histogram
						equalization algorithm to use.
		Returns:
			A frame whose channels have been equalized.
		"""
		# Assertions
		if (self.assertion.assertNumpyType(frame) == False):
			raise ValueError("Frame has to be a numpy array.")
		if (len(frame.shape) != 3):
			raise ValueError("Frame needs to have at least 3 channels.")
		if (equalizationType == None):
			equalizationType = 0
		if (type(equalizationType) != int):
			raise TypeError("ERROR: equalizationType has to be of type int.")
		# Local variables
		equ = np.zeros(frame.shape, np.uint8)
		# Equalize hist
		if (equalizationType == 0):
			for channel in range(3):
				equ[:, :, channel] = cv2.equalizeHist(frame[:, :, channel])
		elif (equalizationType == 1):
			clahe = cv2.createCLAHE(clipLimit=2.0)
			for channel in range(3):
				equ[:, :, channel] = clahe.apply(frame[:, :, channel])
		else:
			raise ValueError("ERROR: equalizationType not understood.")
		if (not (equ.dtype == np.uint8)):
			print("WARNING: Image is not dtype uint8. Forcing type.")
			equ = equ.astype(np.uint8)
		return equ 
Example #20
Source File: facerec_train.py    From deepvisualminer with MIT License 5 votes vote down vote up
def scale(orig_top_dir, scaled_dest_dir, width, height, make_grayscale = True, equalize_hist = False):
    
    if not os.path.exists(scaled_dest_dir):
        os.makedirs(scaled_dest_dir)
    
    for label in os.listdir(orig_top_dir):
        label_dir = os.path.join(orig_top_dir, label)
        dest_label_dir = os.path.join(scaled_dest_dir, label)
        
        if not os.path.exists(dest_label_dir):
            os.mkdir(dest_label_dir)
        
        for imgfilename in os.listdir(label_dir):
            orig_imgfilepath = os.path.join(label_dir, imgfilename)
            print(orig_imgfilepath)
            
            img = cv2.imread(orig_imgfilepath)
            
            if make_grayscale:
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            
                if equalize_hist:
                    print("Equalizing")
                    img = cv2.equalizeHist(img)
                    
            elif equalize_hist:
                print("Warning: Invalid arguments. Histogram equalization can be done only if grayscale is enabled. Ignoring")
            
            img = cv2.resize(img, (width, height))
            
            dest_imgfilepath = os.path.join(dest_label_dir, imgfilename)
            
            cv2.imwrite(dest_imgfilepath, img)
            
            print(orig_imgfilepath,' -> ', dest_imgfilepath) 
Example #21
Source File: dataManage.py    From face_recognition_py with GNU General Public License v3.0 5 votes vote down vote up
def detectFace(self, img):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        if self.isEqualizeHistEnabled:
            gray = cv2.equalizeHist(gray)
        face_cascade = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(90, 90))

        if (len(faces) == 0):
            return None, None
        (x, y, w, h) = faces[0]
        return gray[y:y + w, x:x + h], faces[0]

    # 准备图片数据 
Example #22
Source File: HistogramEqualization.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    image = cv2.imread("../data/4.1.03.tiff", 1)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    red, green, blue = cv2.split(image_rgb)

    eq_red_image = cv2.equalizeHist(red)
    eq_green_image = cv2.equalizeHist(green)
    eq_blue_image = cv2.equalizeHist(blue)

    red_hist = cv2.calcHist([red], [0], None, [256], [0, 255])
    green_hist = cv2.calcHist([green], [0], None, [256], [0, 255])
    blue_hist = cv2.calcHist([blue], [0], None, [256], [0, 255])

    eq_red_hist = cv2.calcHist([eq_red_image], [0], None, [256], [0, 255])
    eq_green_hist = cv2.calcHist([eq_green_image], [0], None, [256], [0, 255])
    eq_blue_hist = cv2.calcHist([eq_blue_image], [0], None, [256], [0, 255])

    channels_images = [red_hist, green_hist, blue_hist]
    equalized_images = [eq_red_hist, eq_green_hist, eq_blue_hist]

    # Channels Histogram
    for i in range(3):
        plt.subplot(4, 1, i + 1)
        plt.plot(channels_images[i], color='g')
        plt.xlim([0, 255])

    plt.show()

    # Channels Equalized Histogram
    for i in range(3):
        plt.subplot(3, 1, i + 1)
        plt.plot(equalized_images[i], color='b')
        plt.xlim([0, 255])

    plt.show() 
Example #23
Source File: img_util.py    From CvStudio with MIT License 5 votes vote down vote up
def histogram_equalization2(img: np.ndarray):
        if len(np.shape(img)) == 3:
            img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
            # equalize the histogram of the Y channel
            img_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0])
            # convert the YUV image back to RGB format
            img = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
        return img 
Example #24
Source File: img_util.py    From CvStudio with MIT License 5 votes vote down vote up
def histogram_equalization(img: np.ndarray):
        if len(np.shape(img)) == 3:
            b, g, r = cv2.split(img)
            red = cv2.equalizeHist(r)
            green = cv2.equalizeHist(g)
            blue = cv2.equalizeHist(b)
            img = cv2.merge((blue, green, red))
        elif len(np.shape(img)) == 1:
            img = cv2.equalizeHist(img)
        return img 
Example #25
Source File: pretreatment.py    From captcha_trainer with Apache License 2.0 5 votes vote down vote up
def equalize_hist(self, value, modify=False) -> np.ndarray:
        if not value:
            return self.origin
        _equalize_hist = cv2.equalizeHist(self.origin)
        if modify:
            self.origin = _equalize_hist
        return _equalize_hist 
Example #26
Source File: gif_frames.py    From captcha_trainer with Apache License 2.0 5 votes vote down vote up
def blend_frame(image_obj, need_frame=None):
    if not need_frame:
        need_frame = [-1]
    img_arr = split_frames(image_obj, need_frame)
    img_arr = blend_arr(img_arr)
    img_arr = cv2.cvtColor(img_arr, cv2.COLOR_RGB2GRAY)
    img_arr = cv2.equalizeHist(img_arr)
    return img_arr 
Example #27
Source File: gif_frames.py    From captcha_trainer with Apache License 2.0 5 votes vote down vote up
def blend_arr(img_arr):
    if len(img_arr) < 1:
        return img_arr
    all_slice = img_arr[0]
    for im_slice in img_arr[1:]:
        all_slice = cv2.addWeighted(all_slice, 0.5, im_slice, 0.5, 0)
    # print(all_slice)
    # all_slice = cv2.equalizeHist(all_slice)
    return all_slice 
Example #28
Source File: app.py    From robovision with GNU General Public License v3.0 5 votes vote down vote up
def detect_face_in_image_data(self, image_data):
        """
        function detects faces in image data,
        draws rectangle for faces in image data,
        and returns this updated image data with highlighted face/s
        """
        self._red = (0, 0, 255)
        self._width = 2
        self._min_size = (30, 30)

        # haarclassifiers work better in black and white
        gray_image = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY)
        gray_image = cv2.equalizeHist(gray_image)

        # path to Haar face classfier's xml file
        face_cascade_xml = './cascades/haarcascades_cuda/" \
                "haarcascade_frontalface_default.xml'
        self.classifier = cv2.CascadeClassifier(face_cascade_xml)
        faces = self.classifier.detectMultiScale(gray_image,
                                                 scaleFactor=1.3,
                                                 minNeighbors=4,
                                                 flags=cv2.CASCADE_SCALE_IMAGE,
                                                 minSize=self._min_size)

        for (x, y, w, h) in faces:
            cv2.rectangle(image_data,
                          (x, y),
                          (x+w, y+h),
                          self._red,
                          self._width)

        return image_data 
Example #29
Source File: dashboard.py    From robovision with GNU General Public License v3.0 5 votes vote down vote up
def detect_faces(self, image: np.ndarray):
        # haarclassifiers work better in black and white
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray_image = cv2.equalizeHist(gray_image)

        faces = self.classifier.detectMultiScale(gray_image,
                                                 scaleFactor=1.3,
                                                 minNeighbors=4,
                                                 flags=cv2.CASCADE_SCALE_IMAGE,
                                                 minSize=self._min_size)

        return faces 
Example #30
Source File: process.py    From BusinessCardReader with MIT License 5 votes vote down vote up
def checkBlur(img):
    img = cv2.resize(img, (1000,600))
    grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    grayImg = cv2.equalizeHist(np.copy(grayImg))
    fft = np.fft.fft(grayImg)
    avgFFT = np.average(fft)
    threshFFT_x, threshFFT_y = np.where(fft> 1.25*avgFFT)
    return len(threshFFT_x) > 130000