def numpy_histogram_backprojection():
    # roi is the object or region of object we need to find
    roi = cv2.imread("rose_red.png")
    hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)

    # target is the image we search in
    target = cv2.imread("rose.png")
    hsvt = cv2.cvtColor(target, cv2.COLOR_BGR2HSV)

    # Find the histograms using calcHist. Can be done with np.histogram2d also
    M = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
    I = cv2.calcHist([hsvt], [0, 1], None, [180, 256], [0, 180, 0, 256])

    # Find the ratio R = M/I. Then backproject R, ie use R as palette and
    # create a new image with every pixel as its corresponding probability of being target
    R = M / I

    h, s, v = cv2.split(hsvt)
    B = R[h.ravel(), s.ravel()]
    B = np.minimum(B, 1)
    B = B.reshape(hsvt.shape[:2])

    # apply a convolution with a circular disc, B = D*B, where D is the disc kernel.
    disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    cv2.filter2D(B, -1, disc, B)
    B = np.uint8(B)
    cv2.normalize(B, B, 0, 255, cv2.NORM_MINMAX)

    # Now the location of maximum intensity gives us the location of object. If we
    # are expecting a region in the image, thresholding for a suitable value gives a nice result.
    ret, thresh = cv2.threshold(B, 50, 255, 0)
Esempio n. 2
0
def plot3(path, site):
    img = cv2.imread(path + site, cv2.IMREAD_COLOR)
    color = ('b', 'g', 'r')
    for i, col in enumerate(color):
        histr = cv2.calcHist([img], [i], None, [256], [0, 256])
        plt.plot(histr, color=col)
        plt.xlim([0, 256])

    img = cv2.imread(path + site, cv2.IMREAD_UNCHANGED)
    chans = cv2.split(img)
    colors = ("b", "g", "r")
    plt.figure()
    plt.title("'Flattened' Color Histogram")
    plt.xlabel("Bins")
    plt.ylabel("# of Pixels")
    features = []

    # loop over the image channels
    for (chan, color) in zip(chans, colors):
        # create a histogram for the current channel and
        # concatenate the resulting histograms for each
        # channel
        hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
        features.extend(hist)

        # plot the histogram
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
    plt.show()
 def find_histogram(self):
     hist_B = cv2.calcHist([self.image_B], [0], None, [256], [self.var1_min, self.var1_max + 1])
     hist_G = cv2.calcHist([self.image_G], [0], None, [256], [self.var2_min, self.var2_max + 1])
     hist_R = cv2.calcHist([self.image_R], [0], None, [256], [self.var3_min, self.var3_max + 1])
     self.image_B = self.apply_outsu(hist_B, self.image_B, self.var1_max, self.var1_min, 'B')
     self.image_G = self.apply_outsu(hist_G, self.image_G, self.var2_max, self.var2_min, 'G')
     self.image_R = self.apply_outsu(hist_R, self.image_R, self.var3_max, self.var3_min, 'R')
Esempio n. 4
0
def process_video(in_file, out_file, width=1920):
    height = 256
    capture = cv2.VideoCapture(in_file)
    n_frames = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
    frames_per_column = int(n_frames / width)
    image = np.zeros((height, width, 3), np.uint8)

    for i_column in xrange(width):
        column1 = np.zeros((height, 1))
        column2 = np.zeros((height, 1))
        column3 = np.zeros((height, 1))
        for _ in xrange(frames_per_column):
            _, frame = capture.read()
            hist1 = cv2.calcHist([frame], [0], None, [256], [0, 256])
            hist2 = cv2.calcHist([frame], [1], None, [256], [0, 256])
            hist3 = cv2.calcHist([frame], [2], None, [256], [0, 256])
            column1 += hist1
            column2 += hist2
            column3 += hist3
        column1 = (column1 / (column1.max() / 255)).astype(np.uint8)
        column2 = (column2 / (column2.max() / 255)).astype(np.uint8)
        column3 = (column3 / (column3.max() / 255)).astype(np.uint8)
        for i, c in enumerate(column1):
            image[i][i_column][0] = c
        for i, c in enumerate(column2):
            image[i][i_column][1] = c
        for i, c in enumerate(column3):
            image[i][i_column][2] = c

    capture.release()

    cv2.imwrite(out_file, image)
    def describeRGB(self, image):
        # compute a multidimensional histogram in the RGB colorspace using information from informaiton defined
        # channels which index is defined by the variable channelIds. Then normalize the histogram so that images
        # with the same content, but either scaled larger or smaller will have (roughly) the same histogram

        if(self.channelIds.shape[0]==1):
            hist = cv2.calcHist([image], self.channelIds,
               None, self.bins, [0, 256])
            hist = cv2.normalize(hist)

        elif(self.channelIds.shape[0]==2):
            hist = cv2.calcHist([image], self.channelIds,
                None, self.bins, [0, 256, 0, 256])
            hist = cv2.normalize(hist)

        elif(self.channelIds.shape[0]==3):
            hist = cv2.calcHist([image], self.channelIds,
                None, self.bins, [0, 256, 0, 256, 0, 256])
            hist = cv2.normalize(hist)
        else:
            print "WARNING: number of channels must be greate or equal to 1"
            hist = np.zeros([8,1])

        # return out 3D histogram as a flattened array
        return hist.flatten()
Esempio n. 6
0
def histoGramRate(img1, img2, formatH):
	hist1 = cv2.calcHist(img1, [0], None, [256], [0.0, 255.0])
	hist2 = cv2.calcHist(img2, [0], None, [256], [0.0, 255.0])

	#cv2.cv.CV_COMP_BHATTACHARYYA
	result = cv2.compareHist(hist1, hist2, formatH)
	print (result)
def hist2d(image):
    chans = cv2.split(image)
    # Move to 2 D histogram
    # number of bins in the histogram from 256 to 32 so we can
    # better visualize the results
    fig = plt.figure()

    # plot 2D color histogram for green and blue
    ax = fig.add_subplot(131)
    hist_gb = cv2.calcHist([chans[1], chans[0]], [0, 1], None, [32, 32], [0, 256, 0, 256])
    p = ax.imshow(hist_gb, interpolation="nearest")
    ax.set_title("2D Color histogram for G and B")
    plt.colorbar(p)

    # plot 2D color histogram for green and red
    ax = fig.add_subplot(132)
    hist_gr = cv2.calcHist([chans[1], chans[2]], [0, 1], None, [32, 32], [0, 256, 0, 256])
    p = ax.imshow(hist_gr, interpolation="nearest")
    ax.set_title("2D Color histogram for G and R")
    plt.colorbar(p)

    # plot 2D color histogram for blue and red
    ax = fig.add_subplot(133)
    hist_br = cv2.calcHist([chans[0], chans[2]], [0, 1], None, [32, 32], [0, 256, 0, 256])
    p = ax.imshow(hist_br, interpolation="nearest")
    ax.set_title("2D Color histogram for B and R")
    plt.colorbar(p)
Esempio n. 8
0
def HistAdjust(img2, gamma_offset=0, silence=True):
    img=np.copy(img2)
    height, width = img.shape
    mpixels=height*width
    hist = cv2.calcHist([img],[0],None,[4],[0,256])
    if silence==False:
        print ("\nchannel mean=%3.3f" %np.mean(img))
        print ("Hist Bands [0]=%3.3f" % (hist[0]/mpixels) )
        print ("Hist Bands [1]=%3.3f" % (hist[1]/mpixels) )
        print ("Hist Bands [2]=%3.3f" % (hist[2]/mpixels) )
        print ("Hist Bands [3]=%3.3f" % (hist[3]/mpixels) )
                
    #----histogram correction invariant to scale

          
    if (hist[0]<mpixels/2.):
        gamma= abs(0.55*mpixels-hist[0])/(0.2*mpixels) +1 + gamma_offset
        img= GammaCorrection(img,gamma)
    else:
        gamma=1 + gamma_offset
        img= GammaCorrection(img,gamma)
        
    hist = cv2.calcHist([img],[0],None,[4],[0,256])
    if silence==False:  
        print ("\nAfter Gamma=%2.2f " %gamma )  
        print ("channel mean=%3.3f" %np.mean(img))
        print ("Hist Bands [0]=%3.3f" % (hist[0]/mpixels) )
        print ("Hist Bands [1]=%3.3f" % (hist[1]/mpixels) )
        print ("Hist Bands [2]=%3.3f" % (hist[2]/mpixels) )
        print ("Hist Bands [3]=%3.3f" % (hist[3]/mpixels) )        
    return img
def make_fg_bg_hist_plot(fg, bg):
    # make a plot comparing color histograms of foreground to background
    f, axarr = plt.subplots(2, 2)
    b, g, r, a = cv2.split(fg)
    bData = np.extract(a>0, b)
    gData = np.extract(a>0, g)
    rData = np.extract(a>0, r)
    axarr[0,0].set_title("Foreground")
    axarr[0,0].set_ylabel("Normalized # of pixels")
    for chan, col in zip([rData, gData, bData], ['red', 'green', 'blue']):
        hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
        hist /= hist.sum() # normalize to compare images of different sizes
        axarr[0,0].plot(hist, color = col)
        axarr[0,0].set_xlim([0, 256])

    b, g, r, a = cv2.split(bg)
    bData = np.extract(a>0, b)
    gData = np.extract(a>0, g)
    rData = np.extract(a>0, r)
    axarr[0,1].set_title("Background")
    for chan, col in zip([rData, gData, bData], ['red', 'green', 'blue']):
        hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
        hist /= hist.sum() # normalize to compare images of different sizes
        axarr[0,1].plot(hist, color = col)
        axarr[0,1].set_xlim([0, 256])
    axarr[1,0].imshow(cv2.cvtColor(fg, cv2.COLOR_BGRA2RGBA))
    axarr[1,1].imshow(cv2.cvtColor(bg, cv2.COLOR_BGRA2RGBA))
    plt.show()
Esempio n. 10
0
def main():
    image = cv2.imread("../data/4.1.03.tiff", 1)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    red_hist = cv2.calcHist([image_rgb], [0], None, [256], [0, 255])
    green_hist = cv2.calcHist([image_rgb], [1], None, [256], [0, 255])
    blue_hist = cv2.calcHist([image_rgb], [2], None, [256], [0, 255])

    # Histogram using Matplotlib
    plt.subplot(3, 1, 1)
    plt.hist(image.ravel(), 256, [0, 255])
    plt.xlim([0, 255])
    plt.title("Image Histogram using Matplotlib")

    # Histogram using Numpy
    plt.subplot(3, 1, 2)
    histogram, bins = np.histogram(image.ravel(), 256, [0, 255])
    plt.plot(histogram, color='r')
    plt.xlim([0, 255])
    plt.title("Image Histogram using Numpy")

    # Histogram using Numpy
    plt.subplot(3, 1, 3)
    plt.plot(red_hist, color='r')
    plt.xlim([0, 255])
    plt.title("Image Histogram using OpenCV")

    plt.show()
def extraerVecinos(imagen1,capitales):
  listaImagenes=[]
  try:
     imagenes = devolverImagenesCapitales(imagen1,capitales)
     img1 = cv2.imread( 'Fotos/'+imagen1 );
     v = cv2.calcHist([img1], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) #Calculo de histograma de imagen
     v = v.flatten()
     hist1 = v / sum(v)
     dictSumas ={}
     for imagen2 in imagenes:
        if not imagen2==imagen1:
          try:
            img2 = cv2.imread( 'Fotos/'+imagen2);
            v = cv2.calcHist([img2], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) #Calculo de histograma de imagen
            v = v.flatten()
            hist2 = v / sum(v)
            d = cv2.compareHist( hist1, hist2, cv2.cv.CV_COMP_INTERSECT) #Calculo de similitud de imagenes
            dictSumas[imagen2] = d             
          except: 
             print "Error"          
     dictSumas = dictSumas.items()
     dictSumas.sort(lambda x,y:cmp(y[1], x[1]))
     i=0
     while i<K: #Devuelve las K imagenes mas similares.
        listaImagenes.append(dictSumas[i][0]) 
        i=i+1 
  except: 
        print "Error"
  return listaImagenes
Esempio n. 12
0
    def new_shading_features(self):
        gray = self.gray()
        edges = self.edges()
        # edges = self.blurred_canny()
        # edges = cv2.Canny(gray, 404/4, 156/4, apertureSize=3)
        height, width = gray.shape
        image = self.hsv()

        ratios = []
        white = []
        window = []
        for tc in [(10,50), (10, 20), (10, 80)]: # topcenter row,col
            h1 = cv2.calcHist( [gray[5:20, 5:width-5]], [0], None, [16], [0, 256] )
            #white.append(np.mean(image[tc[0]-2:tc[0]+2,tc[1]-2:tc[1]+2,0]))
            #white.append(np.mean(image[tc[0]-2:tc[0]+2,tc[1]-2:tc[1]+2,1]))
            #white.append(np.mean(gray[tc[0]-2:tc[0]+2,tc[1]-2:tc[1]+2]))

            center = self.center()
            wy = 4
            wx = 10

            h2 = cv2.calcHist( [gray[center[1]-wy:center[1]+wy, center[0]-wx:center[0]+wx]], [0], None, [160], [0, 256] )

            ws = 2 # window size
            #window.append(np.mean(image[center[1]-ws:center[1]+ws, center[0]-ws:center[0]+ws, 0]))
            #window.append(np.mean(image[center[1]-ws:center[1]+ws, center[0]-ws:center[0]+ws, 1]))
            #window.append(np.mean(gray[center[1]-ws:center[1]+ws, center[0]-ws:center[0]+ws]))

            #ratio = np.array(window) / np.array(white)

            #ratios.append(ratio[1])
            #ratios.append(ratio[2])


        return np.reshape(h2, np.prod(h2.shape)) #[np.mean(ratios)]
Esempio n. 13
0
    def compute_image_histogram(self, feature_labels=None, image_name='', feature_type='SIFT'):
        if feature_type == 'color':
            image_path = settings.MEDIA_ROOT + '/documents/' + image_name
            img = cv2.imread(image_path)
            hist1 = cv2.calcHist([img], [0], None, [60], [0, 256])
            hist2 = cv2.calcHist([img], [1], None, [60], [0, 256])
            hist3 = cv2.calcHist([img], [2], None, [60], [0, 256])
            hist = np.concatenate((hist1, hist2, hist3))
            return hist.transpose()

        elif feature_type == 'GIST':
                image_names = open('media/image_names.txt')
                names = np.genfromtxt(image_names, dtype=str)
                gist_vectors = open('media/gist.txt')
                img_hist = np.genfromtxt(gist_vectors, dtype=str)
                for i in range(len(names)):
                    if names[i] == image_name:
                        return np.array(img_hist[i].split(','), dtype=float)
                return []
        else:
            histograms = open('media/image_histogram.txt')
            img_hists = np.genfromtxt(histograms, dtype=str)
            print img_hists
            for i in range(img_hists.shape[0]):
                if img_hists[i, 0] == image_name:
                    print i
                    return img_hists[i, 1:]
            return []
Esempio n. 14
0
def hist_similarity(image_1, image_2):
    """color hist based image similarity
    
    @param image_1: np.array(the first input image)
    @param image_2: np.array(the second input image)
    @return similarity: float(range from [0,1], the bigger the more similar)
    """
    if image_1.ndim == 2 and image_2.ndim == 2:
        hist_1 = cv2.calcHist([image_1], [0], None, [256], [0.0, 255.0])
        hist_2 = cv2.calcHist([image_2], [0], None, [256], [0.0, 255.0])
        similarity = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CORREL)
    elif image_1.ndim == 3 and image_2.ndim == 3:
        """R,G,B split"""
        b_1, g_1, r_1 = cv2.split(image_1)
        b_2, g_2, r_2 = cv2.split(image_2)
        hist_b_1 = cv2.calcHist([b_1], [0], None, [256], [0.0, 255.0])
        hist_g_1 = cv2.calcHist([g_1], [0], None, [256], [0.0, 255.0])
        hist_r_1 = cv2.calcHist([r_1], [0], None, [256], [0.0, 255.0])
        hist_b_2 = cv2.calcHist([b_2], [0], None, [256], [0.0, 255.0])
        hist_g_2 = cv2.calcHist([g_2], [0], None, [256], [0.0, 255.0])
        hist_r_2 = cv2.calcHist([r_2], [0], None, [256], [0.0, 255.0])
        similarity_b = cv2.compareHist(hist_b_1,hist_b_2,cv2.cv.CV_COMP_CORREL)
        similarity_g = cv2.compareHist(hist_g_1,hist_g_2,cv2.cv.CV_COMP_CORREL)
        similarity_r = cv2.compareHist(hist_r_1,hist_r_2,cv2.cv.CV_COMP_CORREL)
        sum_bgr = similarity_b + similarity_g + similarity_r
        similarity = sum_bgr/3.
    else:
        gray_1 = cv2.cvtColor(image_1,cv2.cv.CV_RGB2GRAY)
        gray_2 = cv2.cvtColor(image_2,cv2.cv.CV_RGB2GRAY)
        hist_1 = cv2.calcHist([gray_1], [0], None, [256], [0.0, 255.0])
        hist_2 = cv2.calcHist([gray_2], [0], None, [256], [0.0, 255.0])
        similarity = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CORREL)
    return similarity
Esempio n. 15
0
    def skin_mask(self, img, det_face_hsv, face_rect):
        """
        Create a mask of the image which returns a binary image (black and white) based
        on whether we thing a section is skin or not. We do this by analyzing the hue and
        saturation from the detected face. From this we can calculate the probability of
        any pixel in the full image occuring in the face image. Then we can filter out
        any values whose probability is below a certain threshold.

        :param img: BGR image from webcam
        :param det_face_hsv: hsv image of the face from the previous detection
        :param face_rect: non-normalized dimensions of face rectangle (left, top, cols, rows)
        :return: 2D array, black and white if pixels are thought to be skin
        """
        #Get the HSV images of the whole thing and the face
        img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        face_left = face_rect[0]
        face_top = face_rect[1]
        face_width = face_rect[2]
        face_height = face_rect[3]
        #create a Hue-Saturation histogram of the face
        hs_face_hist = cv2.calcHist([det_face_hsv], [0,1], None, [32,32], [0, 180,0, 255])
        cv2.normalize(hs_face_hist, hs_face_hist, 0, 255, cv2.NORM_MINMAX)
        #create a Hue-Saturation BackProjection, and a mask
        #This mask ignores dark pixels < 32, and saturated pixels, <60
        hue_min, sat_min, val_min = 0.0, 32.0, 16.0
        mask = cv2.inRange(img_hsv, np.array((hue_min, sat_min, val_min)), np.array((180., 255., 255.)))
        mask_face = mask[face_top:face_top+face_height, face_left:face_left+face_width]
        masked_hs_hist = cv2.calcHist([det_face_hsv], [0,1], mask_face, [32,32], [0, 180,0, 255])
        cv2.normalize(masked_hs_hist, masked_hs_hist, 0, 255, cv2.NORM_MINMAX)
        masked_hs_prob = cv2.calcBackProject([img_hsv], [0,1], masked_hs_hist, [0, 180,0, 255],1)
        cv2.bitwise_and(masked_hs_prob, mask, dst=masked_hs_prob) #seems to lessen noise???
        thresh = 8.0 #threshold likelihood for being skin, changes a lot based on setting
        _, masked_img = cv2.threshold(masked_hs_prob, thresh, 255, cv2.CV_8U) #throw out below thresh

        return masked_img
Esempio n. 16
0
def get_3d_color(image_path):
    image = cv2.imread(image_path)
    img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    # hist = cv2.calcHist([image], [0, 1, 2], None, (8, 3, 3), [0, 180, 0, 256, 0, 256])
    # hist = cv2.normalize(hist).flatten()
    # plt.plot(hist, color='g')
    # plt.xlim([0, 72])

    im = np.array(img)
    temp = copy.deepcopy(im)
    ht = copy.deepcopy(im)

    width = im.shape[0]
    height = im.shape[1]

    for w in range(0, width):
        for h in range(0, height):
            temp[w, h, 0] = h_value(im[w, h, 0])
            temp[w, h, 1] = s_value(im[w, h, 1])
            temp[w, h, 2] = v_value(im[w, h, 2])
            ht[w, h, 0] = im[w, h, 0]/22.5
            ht[w, h, 1] = im[w, h, 1]/(256/3)
            ht[w, h, 2] = im[w, h, 2]/(256/3)

    hist = cv2.calcHist([temp], [0, 1, 2], None, (8, 3, 3), [0, 7, 0, 2, 0, 2])
    hist = [float(x) for x in cv2.normalize(hist, norm_type=cv2.NORM_L1).flatten()]
    plt.plot(hist, color='r')
    plt.xlim([0, 72])
    his = cv2.calcHist([ht], [0, 1, 2], None, (8, 3, 3), [0, 7, 0, 2, 0, 2])
    his = [float(x) for x in cv2.normalize(his, norm_type=cv2.NORM_L1).flatten()]
    plt.plot(his, color='g')
    plt.xlim([0, 72])
    plt.show()
Esempio n. 17
0
def CueBall(BallData):    
    
    data = BallData[1][2]


    #this mask does not reflect the boundary between data and nodata.
    mask = cv2.inRange(data, (0,0,10), (180,255,255))
       
#    cv2.imshow('result1',mask)
#    cv2.imshow('result',data)
#
#    cv2.waitKey(0)
#    cv2.destroyAllWindows()

    
    hist = cv2.calcHist([data], [0], mask, [180], [0, 180])
    
    plt.plot(hist)
    plt.show()
    
    hist = cv2.calcHist([data], [1], mask, [256], [0, 256])
    
    plt.plot(hist)
    plt.show()
    
    hist = cv2.calcHist([data], [2], mask, [256], [0, 256])
    
    plt.plot(hist)
    plt.show()
Esempio n. 18
0
def hist1(img, samimg):
	oriimg = img
	img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
	M = cv2.calcHist([samimg],[0, 1], None, [180, 256], [0, 180, 0, 256] )
	I = cv2.calcHist([img],[0, 1], None, [180, 256], [0, 180, 0, 256] )
	# h,s,v = cv2.split(img)
	# M = np.histogram2d(h.ravel(),s.ravel(),256,[[0,180],[0,256]])[0]
	# h,s,v = cv2.split(samimg)
	# I = np.histogram2d(h.ravel(),s.ravel(),256,[[0,180],[0,256]])[0]

	R = M/(I+1)

	h,s,v = cv2.split(img)
	B = R[h.ravel(), s.ravel()]
	B = np.minimum(B,1)
	B = B.reshape(img.shape[:2])
	disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
	cv2.filter2D(B,-1,disc,B)
	B = np.uint8(B)
	cv2.normalize(B,B,0,255,cv2.NORM_MINMAX)

	ret,thresh = cv2.threshold(B,0,255,0)

	for i in range(oriimg.shape[0]):
		for j in range(oriimg.shape[1]):
			for k in range(oriimg.shape[2]):
				if thresh[i, j] == 0:
					oriimg[i,j] = 0

	cv2.imshow('out', oriimg)
	cv2.waitKey(0)
Esempio n. 19
0
def image_diff_color_hist(lhs_image, rhs_image) -> int:
    diff = 0
    for i in range(lhs_image.shape[2] if len(lhs_image.shape)==3 else 1):
        lhs_hist = cv2.calcHist([lhs_image], [i], None, [32], [0, 256])
        rhs_hist = cv2.calcHist([rhs_image], [i], None, [32], [0, 256])
        diff += cv2.absdiff(lhs_hist, rhs_hist).sum()
    return diff
Esempio n. 20
0
def computeHist(img, center, bbsize):
    mask = zeros(img.shape[:2], uint8)
    mask[center[0]-bbsize:center[0]+bbsize-1, center[1]-bbsize:center[1]+bbsize-1] = 255
    hist1 = cv2.calcHist([img], [0], mask, [256], [0, 256])
    hist2 = cv2.calcHist([img], [1], mask, [256], [0, 256])
    hist3 = cv2.calcHist([img], [2], mask, [256], [0, 256])
    return concatenate((hist1, hist2, hist3), axis=0)
	def Compare_similarity(self, refBox, cropBox):
	# Compute the similarity between two ROI
	# Param 	refBox 	: ROI for reference
	# Param 	cropBox : ROI for comparing
		H1 = cv2.normalize(cv2.calcHist(refBox,  [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])).flatten()
		H2 = cv2.normalize(cv2.calcHist(cropBox, [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])).flatten()
		return cv2.compareHist(H1, H2, cv2.cv.CV_COMP_CORREL)
Esempio n. 22
0
    def Harris_Corner(self):
        self.threshold = 0.999999999999
        temp_i = self.image_i.copy()
        temp1_i = self.image_i.copy()
        gray_i = cv2.cvtColor(temp_i, cv2.COLOR_BGR2GRAY)
        gray_i = numpy.float32(gray_i)
        dst_i = cv2.cornerHarris(gray_i, 2, 3, 0.025)
        dst_i = cv2.dilate(dst_i, None)
        # Threshold for an optimal value, it may vary depending on the image.
        temp_i[dst_i < 0.01 * dst_i.max()] = [0, 0, 0]
        temp1_i[dst_i > 0.01 * dst_i.max()] = [0, 0, 255]
        hist_i = cv2.calcHist([temp_i], [0], None, [256], [0, 256])
        temp_j = self.image_j.copy()
        temp1_j = self.image_j.copy()
        gray_j = cv2.cvtColor(temp_j, cv2.COLOR_BGR2GRAY)
        gray_j = numpy.float32(gray_j)
        dst_j = cv2.cornerHarris(gray_j, 2, 3, 0.025)
        dst_j = cv2.dilate(dst_j, None)
        # Threshold for an optimal value, it may vary depending on the image.
        temp_j[dst_j < 0.01 * dst_j.max()] = [0, 0, 0]
        temp1_j[dst_j > 0.01 * dst_j.max()] = [0, 0, 255]
        hist_j = cv2.calcHist([temp_j], [0], None, [256], [0, 256])

        self.measure = cv2.compareHist(hist_i, hist_j, cv.CV_COMP_CORREL)
        self.assertGreater(self.measure, self.threshold)

        print self.measure
Esempio n. 23
0
def calc_hist(hsv,mask, figure=None, ax1=None, ax2=None):
    chans = cv2.split(hsv)
    # Or maybe I should use Numpy indexing for faster splitting: h=hsv[:,:,0] 
    hist_h = cv2.calcHist([chans[0]], [0], mask, [180], [0, 180])
    hist_s = cv2.calcHist([chans[1]], [0], mask, [256], [0, 256])
    #print hist_s
    hist_h = hist_h.flatten()
    hist_s = hist_s.flatten()
    # Apply Gaussian low pass for histogram (using scipy)
    hist_hg = ndi.gaussian_filter1d(hist_h, sigma=1.5, output=np.float64, mode='nearest')
    hist_sg = ndi.gaussian_filter1d(hist_s, sigma=1.5, output=np.float64, mode='nearest')
    hue_max = np.argmax(hist_hg)
    saturation_max = np.argmax(hist_sg) if np.argmax(hist_sg) >= 20 else 20
    #print hue_max, saturation_max
    #ax1.clear(), ax2.clear()
    #ax1.set_autoscale_on(False)
    # ax1.plot(range(180),hist_hg)
    # ax2.plot(range(256),hist_sg)
    # ax1.set_ylim([0,1200])
    # ax1.set_xlim([0,180])
    # ax2.set_xlim([0,256])
    # ax2.set_ylim([0,1200])
    # figure.canvas.draw()
    #plt.xlim([0, 180])
    lower = np.array([hue_max+20,saturation_max-20,20])
    upper = np.array([hue_max+20,saturation_max+20,255])
    mask_color = cv2.inRange(hsv, lower, upper)
    return hue_max, hist_hg, saturation_max, hist_sg, mask_color
Esempio n. 24
0
def histogram_compare(img, params):
    resolution = 100
    h1 = cv2.calcHist([img], [0], params.fg_mask, [resolution], [0, 1.0])
    h2 = cv2.calcHist([img], [0], params.bg_mask, [resolution], [0, 1.0])
    cv2.normalize(h1, h1, alpha=1, norm_type=1)
    cv2.normalize(h2, h2, alpha=1, norm_type=1)
    return cv2.compareHist(h1, h2, 0)
Esempio n. 25
0
    def matchWithMask(img, mask, threshold=99.0, orig_threshold=70.0, debug=False):
        if len(img.shape) > 2 and img.shape[2] != 1:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Check false-positive
        orig_hist = cv2.calcHist([img], [0], None, [3], [0, 256])
        match2 = orig_hist[2] / np.sum(orig_hist)

        if match2 > orig_threshold:
            # False-Positive condition.
            #print("original %f > orig_threshold %f" % (match2, orig_threshold))
            return False

        ret, thresh1 = cv2.threshold(img, 230, 255, cv2.THRESH_BINARY)
        added = thresh1 + mask
        hist = cv2.calcHist([added], [0], None, [3], [0, 256])

        match = hist[2] / np.sum(hist)

        if debug and (match > threshold):
            print("match2 %f match %f > threshold %f" %
                  (match2, match, threshold))
            cv2.imshow('match_img', img)
            cv2.imshow('match_mask', mask)
            cv2.imshow('match_added', added)
            # cv2.waitKey()

        return match > threshold
def contrast_feature(img):
    hb = cv2.calcHist([img], [0], None, [256], [0, 256]).ravel()
    hg = cv2.calcHist([img], [1], None, [256], [0, 256]).ravel()
    hr = cv2.calcHist([img], [2], None, [256], [0, 256]).ravel()
    hist = hb + hg + hr
    hist = hist/sum(hist)
    return width_center_mass(hist, 0.98)
Esempio n. 27
0
def plot_histogram(**kwargs):
	"""
	Plots one histogram.
	:param img: optional - if provided, will automatically compute the histogram
		of an (colored) image and display it. If provided, greyscale must be also supplied.
	:param greyscale: optional - whether to plot one greyscale histogram or three histograms.
		Must be provided alongside img.
	:param hist: optional - may be either one greyscale or three-channeled histogram.
	"""
	greyscale = False if 'greyscale' not in kwargs else kwargs['greyscale']
	img = None if 'img' not in kwargs else kwargs['img']
	hist = None if 'hist' not in kwargs else kwargs['hist']

	plt.figure()

	if img is not None:
		if greyscale:
			hist = cv2.calcHist([img], [0], None, [256], [0, 256])
		else:
			hist = list()
			for i, col in enumerate(CHANNELS):
				hist += [cv2.calcHist([img], [i], None, [256], [0, 256])]

	if isinstance(hist, list):
		for i, col in enumerate(CHANNELS):
			plt.plot(hist[i], color=col)
			plt.xlim([0, 256])
	else:
		plt.hist(img.ravel(), 256, [0, 256])
Esempio n. 28
0
def findMainColor(image):

	path = os.path.dirname(os.path.abspath(__file__)) + r'/static/'

	imageUrl = path + image

	img = cv2.imread(r'' + str(imageUrl), cv2.IMREAD_COLOR)

	if img == None:

		imageUrl = path + 'default.jpg'
		img = cv2.imread(imageUrl, cv2.IMREAD_COLOR)

	imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

	histH = cv2.calcHist([imgHsv],[0], None, [180],[0,180])
	histS = cv2.calcHist([imgHsv], [1], None, [256], [0,256])
	histV = cv2.calcHist([imgHsv], [2], None, [256], [0,256])

	maxTuple = ( [i for i,j in enumerate(histH) if j == max(histH)][0],
				 [i for i,j in enumerate(histS) if j == max(histS)][0],
				 [i for i,j in enumerate(histV) if j == max(histV)][0])

	color = np.uint8([[[maxTuple[0],maxTuple[1],maxTuple[2]]]])
	mainColor = cv2.cvtColor(color, cv2.COLOR_HSV2RGB)
	mainColor = (list(mainColor)[0][0][0], list(mainColor)[0][0][1], list(mainColor)[0][0][2])

	return mainColor
Esempio n. 29
0
def hw5(cmp_foo):
    os.chdir(os.path.dirname(__file__) + "/datasets/Corel")
    list_dir = [filename for filename in os.listdir(os.getcwd()) if not filename.endswith(".txt")]
    results = []

    # params for cv2.calcHist()
    channels_hist = [0, 1, 2]    # H, S, V channels
    mask_hist = None
    bins_hist = [12, 12, 12]
    range_hist = [0, 256, 0, 256, 0, 256]

    for i in range(len(list_dir)):
        image = cv2.imread(list_dir[i], cv2.IMREAD_COLOR)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

        hist = cv2.calcHist([image], channels_hist, mask_hist, bins_hist, range_hist)
        hist = cv2.normalize(hist).flatten()

        for j in range(i + 1, len(list_dir)):
            image_second = cv2.imread(list_dir[j], cv2.IMREAD_COLOR)
            image_second = cv2.cvtColor(image_second, cv2.COLOR_BGR2HSV)

            hist_second = cv2.calcHist([image_second],  channels_hist, mask_hist, bins_hist, range_hist)
            hist_second = cv2.normalize(hist_second).flatten()

            results.append((cmp_foo(hist, hist_second), list_dir[i], list_dir[j]))

    with open(cmp_foo.__name__ + ".txt", "w+") as f:
        for res in sorted(results):
            f.write(res[1] + " " + res[2] + " " + str(res[0]) + "\n")
Esempio n. 30
0
    def calculateHistogram(self, image, bb=None):
        '''
        :param image: input image
        :type image: numpy.ndarray
        :param bb: bounding box
        :type bb: numpy.ndarray
        If bb (=(x, y, w, h)) is not None, the histogram is taken from the bounded
        part of the image. If use_background is True, bb cannot be None

        .. note::
            The bounding box here is given in pixel coordinates!
        '''
        assert not (self.use_background and bb is None), 'If using background, bb must be provided'

        if bb is not None:
            x, y, w, h = bb
            target = image[y:y + h, x:x + w]
        else:
            target = image
        hist_target = cv2.calcHist([target], channels=self._channels, mask=None, histSize=self.n_bins, ranges=self._ranges)
        if self.raw_hist_target is None:
            self.raw_hist_target = hist_target
        else:
            self.raw_hist_target += hist_target

        if self.use_background:
            hist_image = cv2.calcHist([image], channels=self._channels, mask=None, histSize=self.n_bins, ranges=self._ranges)
            if self.raw_hist_image is None:
                self.raw_hist_image = hist_image
            else:
                self.raw_hist_image += hist_image
        self._update_hist()
Esempio n. 31
0
            w/=2
            h/=2

            print(w,h,"after croping we have to resize the image to this dimmensions")

            cv2.imshow('real image', img)
            cv2.waitKey(0)
            print("for 10%")
            print(x1,y1)




img = cv2.imread(r"C:\Users\dell\Desktop\project\Dr._Viswanath\us_6144x4415pixels_113dpi_24bitdepth\W10_017_3ms_(7).tif")    

histg = cv2.calcHist([img],[2],None,[256],[0,256])
a=[]
#for i in range(len(histg)):
for i in range(255):
    a.append(histg[i][0])
plt.plot(a)


img= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#resize the image

scale_percent = 10 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
print(width,height)
Esempio n. 32
0
def track_ball_3(video):
    """
    As track_ball_1, but for ball_3.mov.

    Requires going through the video once to find the size of the moving
    object, then again to track its location
    """
    result = []
    num_frames = 0
    fgbg = cv2.BackgroundSubtractorMOG()
    x, y, w, h = 0, 0, 0, 0
    avg_w, avg_h = 0, 0

    ret, frame = video.read()

    while ret is True:
        num_frames = num_frames + 1
        sub = fgbg.apply(frame)

        kernel = numpy.ones((5, 5), numpy.uint8)
        dilation = cv2.dilate(sub, kernel, iterations=1)
        ret, thresh = cv2.threshold(dilation, 127, 255, 0)

        # contours is a list of all the contours in the image
        contours, _ = cv2.findContours(thresh, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)

        if (contours):
            x, y, w, h = cv2.boundingRect(contours[0])
            avg_w = avg_w + w
            avg_h = avg_h + h

        ret, frame = video.read()

    avg_w = avg_w / num_frames
    avg_h = avg_h / num_frames

    # Reset the video
    video.set(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO, 0)

    # take first frame of the video
    ret, frame = video.read()

    # setup initial location of window to track an object of the
    # size determined previously
    track_window = (avg_w, avg_w, avg_h, avg_h)
    x, y, w, h = track_window

    # set up the ROI for tracking
    roi = frame[y:y + h, x:x + w]
    hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv_roi, numpy.array((0., 60., 32.)),
                       numpy.array((180., 255., 255.)))
    roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
    cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

    # setup the termination criteria,
    # either 10 iteration or move by atleast 1 pt
    term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)

    while ret is True:

        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)

        # apply meanshift to get the new location
        ret, track_window = cv2.meanShift(dst, track_window, term_crit)

        # draw it on image
        x, y, w, h = track_window
        result.append((x, y, x + w, y + h))

        ret, frame = video.read()

    return result
Esempio n. 33
0
    else:
        return path_number


# TARGET_FILE = 'train_0000.jpg'
IMG_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../data/temp/'
IMG_SIZE = (200, 200)
temp = 0

for i in range(6901):
    # print(i)
    j = i + 1
    i = str(i)
    j = str(j)
    i = add_zeros(i)
    j = add_zeros(j)

    target_img_path = IMG_DIR + 'train_' + i + '.jpg'
    target_img = cv2.imread(target_img_path)
    target_img = cv2.resize(target_img, IMG_SIZE)
    target_hist = cv2.calcHist([target_img], [0], None, [256], [0, 256])

    comparing_img_path = IMG_DIR + 'train_' + j + '.jpg'
    # print('FILE: %s : %s' % ('train_' + i + '.jpg', 'train_' + j + '.jpg'))
    comparing_img = cv2.imread(comparing_img_path)
    comparing_img = cv2.resize(comparing_img, IMG_SIZE)
    comparing_hist = cv2.calcHist([comparing_img], [0], None, [256], [0, 256])
    ret = cv2.compareHist(target_hist, comparing_hist, 0)
    # print(file, ret)
    print(ret - temp)
    temp = ret
Esempio n. 34
0
    '/media/pc/ntfs/downloads/Waterloo tennis Rodrigo 15_06_2016.mp4')

for i in range(6000):
    ret, frame = cap.read()
    frame = cv2.resize(frame,
                       None,
                       fx=0.5,
                       fy=0.5,
                       interpolation=cv2.INTER_CUBIC)

r, h, c, w = 150, 120, 260, 90
track_window = (c, r, w, h)
roi = frame[r:r + h, c:c + w]
hsv_roi = roi  #cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
##mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([roi], [0, 1], None, [256, 256], [0, 256, 0, 256])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)

while (1):
    ret, frame = cap.read()
    if not (ret):
        break
    frame = cv2.resize(frame,
                       None,
                       fx=0.5,
                       fy=0.5,
                       interpolation=cv2.INTER_CUBIC)
    hsv = frame  #cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    dst = cv2.calcBackProject([hsv], [0, 1], roi_hist, [0, 256, 0, 256], 1)
img3 = cv2.imread('../img/taekwonv3.jpg')
img4 = cv2.imread('../img/dr_ochanomizu.jpg')

cv2.imshow('query', img1)
imgs = [img1, img2, img3, img4]
hists = []

for i, img in enumerate(imgs) :
    plt.subplot(1,len(imgs),i+1)
    plt.title('img%d'% (i+1))
    plt.axis('off') 
    plt.imshow(img[:,:,::-1])
    
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    hist = cv2.calcHist([hsv], [0,1], None, [180,256], [0,180,0, 256])
    
    cv2.normalize(hist, hist, 0, 1, cv2.NORM_MINMAX)
    hists.append(hist)


query = hists[0]
methods = {'CORREL' :cv2.HISTCMP_CORREL, 'CHISQR':cv2.HISTCMP_CHISQR, 
           'INTERSECT':cv2.HISTCMP_INTERSECT,
           'BHATTACHARYYA':cv2.HISTCMP_BHATTACHARYYA}

for j, (name, flag) in enumerate(methods.items()):
    print('%-10s'%name, end='\t')
    for i, (hist, img) in enumerate(zip(hists, imgs)):
        ret = cv2.compareHist(query, hist, flag)
        if flag == cv2.HISTCMP_INTERSECT:
except getopt.GetoptError:
    print("error in arguments")
    sys.exit(2)

for i in range(0, len(args)):

    if args[i] == "--input":
        filename = args[i + 1]
    elif args[i] == "--output":
        outputfile = args[i + 1]
    elif i == 3:
        n = int(args[i])

# Calculation of histogram on the image.
img = cv2.imread(filename, 0)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])


# Function to avoid zero error.
def avoidzero(first, second):
    try:
        if second == 0:
            return 0
        else:
            return (first / second)
    except:
        return 0


# Initialization of the variables.
gsize = math.sqrt(n)
Esempio n. 37
0
        #newRGBImage = cv2.merge((b,g,r))

        #hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        lower_bounded = np.array([0, 0, 0])
        upper_bounded = np.array([0, 255, 0])

        mask = cv2.inRange(frame, lower_bounded, upper_bounded)

        newframe = cv2.bitwise_and(frame, frame, mask=mask)

        cv2.imshow('RGB', frame)
        cv2.imshow('mask', mask)
        cv2.imshow('res', newframe)

        histogramR = cv2.calcHist([r], [0], None, [bins], [0, 255]) / numPixels
        histogramG = cv2.calcHist([g], [0], None, [bins], [0, 255]) / numPixels
        histogramB = cv2.calcHist([b], [0], None, [bins], [0, 255]) / numPixels
        lineR.set_ydata(histogramR)
        lineG.set_ydata(histogramG)
        lineB.set_ydata(histogramB)
    else:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('Grayscale', gray)
        histogram = cv2.calcHist([gray], [0], None, [bins],
                                 [0, 255]) / numPixels
        lineGray.set_ydata(histogram)

    fig.canvas.draw()

    key = cv2.waitKey(20)
Esempio n. 38
0
#@Software : PyCharm
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

cap = cv.VideoCapture("./image/DOG.wmv")

# 指定追踪目标
ret, frame = cap.read()
r, h, c, w = 197, 141, 0, 208
win = (c, r, w, h)
roi = frame[r:r + h, c:c + w]

# 计算直方图
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
roi_hist = cv.calcHist(hsv_roi, [0], None, [180], [0, 180])
cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX)

# 目标追踪
term = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1)
while (True):
    ret, frame = cap.read()
    if ret == True:
        hst = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        dst = cv.calcBackProject([hst], [0], roi_hist, [0, 180], 1)
        ret, win = cv.meanShift(dst, win, term)

        x, y, w, h = win
        img2 = cv.rectangle(frame, (x, y), (x + w, y + h), 255, 2)
        cv.imshow("frame", img2)
        if cv.waitKey(60) & 0xFF == ord('q'):
def AverageHistogram():
    mean_b = []
    mean_g = []
    mean_r = []

    std_dev_b = []
    std_dev_g = []
    std_dev_r = []
    histogram_r = np.zeros((255, 1))
    histogram_g = np.zeros((255, 1))
    histogram_b = np.zeros((255, 1))

    # Iterate for no of green buoy images
    for i in range(0, green_data):
        string_path = path + "\orange" + str(i) + ".jpg"
        img = cv.imread(string_path)
        color = ("b", "g", "r")

        # New Mean Calculation
        mask = np.zeros((img.shape[0], img.shape[0], 3), np.uint8)
        coordinates = np.indices((img.shape[0], img.shape[0]))
        coordinates = coordinates.reshape(2, -1)
        x, y = coordinates[0], coordinates[1]
        indices = np.where(img[x, y] != [0, 0, 0])
        xnew, ynew = x[indices[0]], y[indices[0]]
        mask[xnew, ynew] = img[xnew, ynew]
        #cv.imshow("e",mask)
        pixels = img[xnew, ynew]
        mean = np.sum(pixels, axis=0) / len(pixels)
        stds = [
            np.std(pixels[:, 0]),
            np.std(pixels[:, 1]),
            np.std(pixels[:, 2])
        ]

        for j, c in enumerate(color):
            if c == "b":
                temp_b = cv.calcHist([img], [j],
                                     None,
                                     hist_size,
                                     hist_range,
                                     accumulate=1)
                histogram_b = np.column_stack((histogram_b, temp_b))
                mean_b.append(mean[0])
                std_dev_b.append(stds[0])
            if c == "g":
                temp_g = cv.calcHist([img], [j],
                                     None,
                                     hist_size,
                                     hist_range,
                                     accumulate=1)
                histogram_g = np.column_stack((histogram_g, temp_g))
                mean_g.append(mean[1])
                std_dev_g.append(stds[1])
            if c == "r":
                temp_r = cv.calcHist([img], [j],
                                     None,
                                     hist_size,
                                     hist_range,
                                     accumulate=1)
                histogram_r = np.column_stack((histogram_r, temp_r))
                mean_r.append(mean[2])
                std_dev_r.append(stds[2])

    histogram_avg_b = np.sum(histogram_b, axis=1) / (green_data)
    histogram_avg_g = np.sum(histogram_g, axis=1) / (green_data)
    histogram_avg_r = np.sum(histogram_r, axis=1) / (green_data)

    #Uncomment to plot histograms
    #plt.subplot(3,1,1)
    #plt.plot(histogram_avg_b, color = "b")
    #plt.subplot(3,1,2)
    #plt.plot(histogram_avg_g, color = "g")
    #plt.subplot(3,1,3)
    #plt.plot(histogram_avg_r, color = "r")
    #plt.show()

    return mean_r, mean_g, mean_b, std_dev_r, std_dev_g, std_dev_b
    images.append(image)

hitogram_b = np.zeros((256, 1))
hitogram_g = np.zeros((256, 1))
hitogram_r = np.zeros((256, 1))

for image in images:
    imgr = cv2.imread("%s%s" % (path, image))

    #imgr = img[2,:,:]
    img = cv2.GaussianBlur(imgr, (5, 5), 0)
    #print(np.shape(img))
    color = ("b", "g", "r")
    for i, col in enumerate(color):
        if col == 'b':
            histr_b = cv2.calcHist([img], [i], None, [256], [0, 256])
            #print(histr_b.shape)
            hitogram_b = np.column_stack((hitogram_b, histr_b))

            #print(histr)
            #plt.plot(histr_b,color = col)
            #plt.xlim([0,256])
        if col == 'g':
            histr_g = cv2.calcHist([img], [i], None, [256], [0, 256])
            #print(histr_g.shape)
            hitogram_g = np.column_stack((hitogram_g, histr_g))
            #print(histr)
            #plt.plot(histr_g,color = col)
            #plt.xlim([0,256])
        if col == 'r':
            histr_r = cv2.calcHist([img], [i], None, [256], [0, 256])
Esempio n. 41
0
import matplotlib.pyplot as plt
import cv2


def getGrayHistImage(hist):
    imgHist = np.full((100, 256), 255, dtype=np.uint8)

    histMax = np.max(hist)
    for x in range(256):
        pt1 = (x, 100)
        pt2 = (x, 100 - int(hist[x, 0] * 100 / histMax))
        cv2.line(imgHist, pt1, pt2, 0)

    return imgHist


src = cv2.imread('lenna.bmp', cv2.IMREAD_GRAYSCALE)

if src is None:
    print('Image load failed!')
    sys.exit()

hist = cv2.calcHist([src], [0], None, [256], [0, 256])
histImg = getGrayHistImage(hist)

cv2.imshow('src', src)
cv2.imshow('histImg', histImg)
cv2.waitKey()

cv2.destroyAllWindows()
Esempio n. 42
0
import numpy as np
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])

img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", image)

plt.figure()
plt.title("gray hist")
hist = cv2.calcHist(img, [0], None, [256], [0, 256])
plt.plot(hist)

ch = cv2.split(image)
colors = ("b", "g", "r")

plt.figure()
plt.title("color Histogram")
plt.xlabel("Bins")
plt.ylabel("# of pixels")

for (chan, color) in zip(ch, colors):
    hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])
def extract_color_histogram(image,bins=(8,8,8)):

#extract a 3D color histogramfrom the HSV color space using the supplies numbr of 'bins' per channel.
 hsv = cv2.cvtcolor(image,cv2.COLOR_BGR2HSV)
 hist = cv2.calcHist([hsv], [0,1,2], None, bins, [0,180,0,256,0,256])
Esempio n. 44
0
            It the index of channel for which we calculate histogram. 
            For example, if input is grayscale image, its value is [0]. 
            For color image, you can pass [0],[1] or [2] to calculate 
            histogram of blue,green or red channel respectively.
    mask : mask image. To find histogram of full image, it is given as “None”.
            But if you want to find histogram of particular region of image, 
            you have to create a mask image for that and give it as mask.
    histSize : this represents our BIN count. Need to be given in 
            square brackets. For full scale, we pass [256].
    ranges : this is our RANGE. Normally, it is [0,256].
"""

img = cv2.imread('../../Media Files/input_images/img_5.jpg')
blue_hist = cv2.calcHist(images=[img],
                         channels=[0],
                         mask=None,
                         histSize=[256],
                         ranges=[0, 256])
green_hist = cv2.calcHist(images=[img],
                          channels=[1],
                          mask=None,
                          histSize=[256],
                          ranges=[0, 256])
red_hist = cv2.calcHist(images=[img],
                        channels=[2],
                        mask=None,
                        histSize=[256],
                        ranges=[0, 256])
plt.subplot(2, 2, 1), plt.plot(blue_hist,
                               color="b"), plt.title("Blue Histogram")
plt.subplot(2, 2, 2), plt.plot(green_hist,
            H[i] = H[i] + 1
    return H


file = ['jpg', 'gif', 'png', 'bmp', 'tif']
name = 'image'
i = 3
for img_type in file:
    pil_img = Image.open(name + '.' + img_type).convert('RGB')
    cv_img = np.array(pil_img)
    img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    split_img = cv2.split(img)
    #o_hist = cv2.calcHist(gray_img,[1],None,[255],[0,255])
    o_hist2 = gray_histogram(gray_img)
    b_hist = cv2.calcHist(split_img, [0], None, [255], [0, 255])
    g_hist = cv2.calcHist(split_img, [1], None, [255], [0, 255])
    r_hist = cv2.calcHist(split_img, [2], None, [255], [0, 255])
    plt.subplot(6, 2, i)
    plt.plot(o_hist2)
    plt.text(10, 50, 'gray' + img_type)
    i = i + 1
    plt.subplot(6, 2, i)
    plt.plot(b_hist, color='b')
    plt.plot(g_hist, color='g')
    plt.plot(r_hist, color='r')
    plt.text(10, 20000, 'RGB' + img_type)
    i = i + 1

plt.subplot(6, 2, 1), plt.imshow(gray_img, cmap='gray')
plt.subplot(6, 2, 2), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
Esempio n. 46
0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
hog = cv2.HOGDescriptor()
detector = cv2.HOGDescriptor_getDefaultPeopleDetector()
hog.setSVMDetector(detector)

found, wight = hog.detectMultiScale(gray)
index = 2
track_window = tuple(found[index])
print(track_window)
roi = frame[found[index][1]:found[index][1] + found[index][3],
            found[index][0]:found[index][0] + found[index][2]]
print(found[index])
hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                   np.array((180., 255., 255.)))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
while cap.isOpened():
    ret, frame = cap.read()
    p1 = (int(found[index][0]), int(found[index][1]))
    p2 = (int(found[index][0] + found[index][2]),
          int(found[index][1] + found[index][3]))
    cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
    if ret == True:
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)
        ret, track_window = cv2.CamShift(dst, track_window, term_crit)

        pts = cv2.boxPoints(ret)
Esempio n. 47
0
def process(inpath, outpath, tolerance):
    original_image = cv2.imread(inpath)
    tolerance = int(tolerance) * 0.01

    #Get properties
    width, height, channels = original_image.shape

    color_image = original_image.copy()

    blue_hist = cv2.calcHist([color_image], [0], None, [256], [0, 256])
    green_hist = cv2.calcHist([color_image], [1], None, [256], [0, 256])
    red_hist = cv2.calcHist([color_image], [2], None, [256], [0, 256])

    blue_mode = blue_hist.max()
    blue_tolerance = np.where(blue_hist == blue_mode)[0][0] * tolerance
    green_mode = green_hist.max()
    green_tolerance = np.where(green_hist == green_mode)[0][0] * tolerance
    red_mode = red_hist.max()
    red_tolerance = np.where(red_hist == red_mode)[0][0] * tolerance

    sloop_blue = calc_sloop_change(blue_hist, blue_mode, blue_tolerance)
    sloop_green = calc_sloop_change(green_hist, green_mode, green_tolerance)
    sloop_red = calc_sloop_change(red_hist, red_mode, red_tolerance)

    gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
    gray_hist = cv2.calcHist([original_image], [0], None, [256], [0, 256])

    largest_gray = gray_hist.max()
    threshold_gray = np.where(gray_hist == largest_gray)[0][0]

    #Red cells
    gray_image = cv2.adaptiveThreshold(gray_image, 255,
                                       cv2.ADAPTIVE_THRESH_MEAN_C,
                                       cv2.THRESH_BINARY, 85, 4)

    _, contours, hierarchy = cv2.findContours(gray_image, cv2.RETR_LIST,
                                              cv2.CHAIN_APPROX_SIMPLE)

    c2 = [i for i in contours if cv2.boundingRect(i)[3] > 15]
    cv2.drawContours(color_image, c2, -1, (0, 0, 255), 1)

    cp = [
        cv2.approxPolyDP(i, 0.015 * cv2.arcLength(i, True), True) for i in c2
    ]

    countRedCells = len(c2)

    for c in cp:
        xc, yc, wc, hc = cv2.boundingRect(c)
        cv2.rectangle(color_image, (xc, yc), (xc + wc, yc + hc), (0, 255, 0),
                      1)

    #Malaria cells
    gray_image = cv2.inRange(original_image,
                             np.array([sloop_blue, sloop_green, sloop_red]),
                             np.array([255, 255, 255]))

    _, contours, hierarchy = cv2.findContours(gray_image, cv2.RETR_LIST,
                                              cv2.CHAIN_APPROX_SIMPLE)

    c2 = [i for i in contours if cv2.boundingRect(i)[3] > 8]
    cv2.drawContours(color_image, c2, -1, (0, 0, 0), 1)

    cp = [cv2.approxPolyDP(i, 0.15 * cv2.arcLength(i, True), True) for i in c2]

    countMalaria = len(c2)

    for c in cp:
        xc, yc, wc, hc = cv2.boundingRect(c)
        cv2.rectangle(color_image, (xc, yc), (xc + wc, yc + hc), (0, 0, 0), 1)

    #Write image
    cv2.imwrite(outpath, color_image)

    #Write statistics
    with open(outpath + '.stats', mode='w') as f:
        f.write(str(countRedCells) + '\n')
        f.write(str(countMalaria) + '\n')
Esempio n. 48
0
import cv2
import numpy as np
import matplotlib.pyplot as pyplot

image = cv2.imread("orange.jpg", 0)
lut = np.zeros(256, dtype=image.dtype)  # 创建空的查找表
hist = cv2.calcHist(
    [image],  # 计算图像的直方图
    [0],  # 使用的通道
    None,  # 没有使用mask
    [256],  # it is a 1D histogram
    [0.0, 255.0])

minBinNo, maxBinNo = 0, 255

# 计算从左起第一个不为0的直方图柱的位置
print(hist)
for binNo, binValue in enumerate(hist):
    if binValue != 0:
        minBinNo = binNo
        break
# 计算从右起第一个不为0的直方图柱的位置
for binNo, binValue in enumerate(reversed(hist)):
    if binValue != 0:
        maxBinNo = 255 - binNo
        break

print(minBinNo, " ", maxBinNo)

# 生成查找表,方法来自参考文献1第四章第2节
for i, v in enumerate(lut):
def compute_entropy( img ):
	hist = cv2.calcHist([img], [0], None, [256], [0,256] ) 
	hist = hist.ravel() / hist.sum()
	logs = np.log2( hist + 1e-4 )
	entropy = -1 * (hist*logs).sum()
	return entropy
Esempio n. 50
0
import cv2
import numpy as np
import matplotlib.pylab as plt

img = cv2.imread('../../../../../img/abnormal.jpg', cv2.IMREAD_GRAYSCALE)
img_f = img.astype(np.float32)

img_norm = ((img_f - img_f.min()) * (255) / (img_f.max() - img_f.min()))
img_norm = img_norm.astype(np.uint8)
img_norm2 = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)

hist = cv2.calcHist([img], [0], None, [256], [0, 255])
hist_norm = cv2.calcHist([img_norm], [0], None, [256], [0, 255])
hist_norm2 = cv2.calcHist([img_norm2], [0], None, [256], [0, 255])

cv2.imshow('Before', img)
cv2.imshow('Manual', img_norm)
cv2.imshow('cv2.normalize()', img_norm2)

hists = {'Before': hist, 'Manual': hist_norm, 'cv2.normalize()': hist_norm2}
for i, (k, v) in enumerate(hists.items()):
    plt.subplot(1, 3, i + 1)
    plt.title(k)
    plt.plot(v)

plt.show()
Esempio n. 51
0
def createImg(input):
    if input == 0:
        """ create a img filled with zeros"""
        img = np.zeros((500, 500), dtype=np.int16)
    elif input == 1:
        """ create a img filled with ones"""
        img = np.ones((500, 500), dtype=np.float32)
    elif input == 2:
        """ create a img filled with a scalar"""
        img = 127 * np.ones((500, 500), dtype=np.int16)
    elif input == 3:
        """ Initializing a grayscale image with random values, uniformly distributed"""
        img = np.ones((250, 250), dtype=np.uint8)
        cv2.randu(img, 0, 255)
    elif input == 4:
        """ Initializing a color image with random values, uniformly distributed """
        img = np.ones((250, 250, 3), dtype=np.uint8)
        bgr = cv2.split(img)
        cv2.randu(bgr[0], 0, 255)
        cv2.randu(bgr[1], 0, 255)
        cv2.randu(bgr[2], 0, 255)
        img = cv2.merge(bgr)
    elif input == 5:
        """ Initializing a grayscale image with random values, normally distributed """
        img = np.ones((250, 250), dtype=np.uint8)
        cv2.randn(img, 127, 40)
    elif input == 6:
        """ Initializing a color image with random values, normally distributed """
        img = np.ones((250, 250, 3), dtype=np.uint8)
        bgr = cv2.split(img)
        cv2.randn(bgr[0], 127, 40)
        cv2.randn(bgr[1], 127, 40)
        cv2.randn(bgr[2], 127, 40)
        img = cv2.merge(bgr)
    elif input == 7:
        """ Initialize a color grayscale with uniformly distributed random values and visualize its histogram """
        img = np.ones((250, 250), dtype=np.uint8)
        cv2.randu(img, 0, 255)
        plt.title("Histogram")
        plt.hist(img.ravel(), 256, [0, 256])
        plt.show()
        return
    elif input == 8:
        """ Initialize a color image with uniformly distributed random values and visualize its histogram """
        img = np.ones((250, 250, 3), dtype=np.uint8)
        bgr = cv2.split(img)
        cv2.randu(bgr[0], 0, 255)
        cv2.randu(bgr[1], 0, 255)
        cv2.randu(bgr[2], 0, 255)
        img = cv2.merge(bgr)
        color = ('b', 'g', 'r')
        for i, col in enumerate(color):
            histr = cv2.calcHist([img], [i], None, [256], [0, 256])
            plt.plot(histr, color=col)
            plt.xlim([0, 256])
        plt.show()
        return
    elif input == 9:
        """ Initialize a grayscale image with normally distributed random values and visualize its histogram """
        img = np.ones((250, 250), dtype=np.uint8)
        cv2.randn(img, 127, 40)
        plt.title("Histogram")
        plt.hist(img.ravel(), 256, [0, 256])
        plt.show()
        return
    elif input == 10:
        """ Initialize a color image with normally distributed random values and visualize its histogram """
        img = np.ones((250, 250, 3), dtype=np.uint8)
        bgr = cv2.split(img)
        cv2.randn(bgr[0], 127, 40)
        cv2.randn(bgr[1], 127, 40)
        cv2.randn(bgr[2], 127, 40)
        img = cv2.merge(bgr)
        color = ('b', 'g', 'r')
        for i, col in enumerate(color):
            histr = cv2.calcHist([img], [i], None, [256], [0, 256])
            plt.plot(histr, color=col)
            plt.xlim([0, 256])
        plt.show()
        return
    elif input == 11:
        """  Convert image to different ranges """
        img = np.ones((3, 3), dtype=np.float32)
        cv2.randn(img, 0, 1)
        print("Normally distributed random values = \n", img, "\n\n")
        cv2.normalize(img, img, 255, 0, cv2.NORM_MINMAX)
        print("Normalized = \n", img, "\n\n")
        img = np.asarray(img, dtype=np.uint8)
        print("Converted to uint8 = \n", img, "\n\n")
        img = 255 * img
        img = np.asarray(img, dtype=np.uint8)
        print(img, "\n\n")
        return
    elif input == 12:
        """ Create random images continuously """
        img = np.ones((250, 250), dtype=np.uint8)
        while cv2.waitKey(0) != ord('q'):
            cv2.randn(img, 120, 60)
            cv2.imshow("img", img)
        return
    cv2.imshow("img", img)
from matplotlib import pyplot as plt

# np.set_printoptions(threshold=np.inf)
'''
直方图反投影:如果一幅图像的区域中显示的是一种机构纹理或者一个独特物体,
那么这个区域的直方图可以看作一个概率函数,它给的是某个像素属于该纹理或物体的概率。
所谓反向投影就是首先计算某一特征的直方图模型,然后使用模型去寻找测试图像中存在的该特征
'''
'''Numpy算法实现>>>>>>>>>>>>>>>>>'''
# 1. 首先计算需要寻找的目标物体的颜色直方图M和整体图片的直方图I
roi = cv2.imread('../../images/flower-part.png')
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)

target = cv2.imread('../../images/flower-full.jpg')
hsvt = cv2.cvtColor(target, cv2.COLOR_BGR2HSV)
M = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
I = cv2.calcHist([hsvt], [0, 1], None, [180, 256], [0, 180, 0, 256])

# 2. 计算比率 R=M/I, 反投影R, 把R看作调色板,创建一幅图像,图像的每个像素作为其对应的目标概率
# B(x,y) = R[h(x,y),s(x,y)], h=hue,s=saturation
R = M / (I + 1)
h, s, v = cv2.split(hsvt)
B = R[h.ravel(), s.ravel()]
B = np.minimum(B, 1)
B = B.reshape(hsvt.shape[:2])

# 3. 创建并应用卷积核
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))  # 5*5椭圆卷积核
cv2.filter2D(B, -1, disc, B)
B = np.uint8(B)
cv2.normalize(B, B, 0, 255, cv2.NORM_MINMAX)
Esempio n. 53
0
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('lena.jpg')  # 入力画像を読み込む
color = ('b', 'g', 'r')
for i, col in enumerate(color):
    histr = cv2.calcHist([img], [i], None, [256], [0, 256])  # ヒストグラムの算出
    plt.plot(histr, color=col)  # ヒストグラムの表示
plt.xlim([0, 256])
plt.show()
Esempio n. 54
0
import cv2
import numpy as np

import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt

#img = cv2.imread('hero1.jpg',0)
img = cv2.imread(
    '/Users/rputra/CODE/Histogram/video_data/Training/a1_s1_t1_1.png', 0)
# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 180:450] = 255
masked_img = cv2.bitwise_and(img, img, mask=mask)
# Calculate histogram with mask and without mask
# Check third argument for mask
hist_full = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_mask = cv2.calcHist([img], [0], mask, [256], [0, 256])
print(hist_full)
plt.subplot(221), plt.imshow(img, 'gray')
plt.subplot(222), plt.imshow(mask, 'gray')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.xlim([0, 256])
plt.show()
Esempio n. 55
0
def FrameChange(ssi_array, frames_jpg_path, all_frames):
    # this function finds the frames at the shot boundary
    # length of ssi_array, how many adjacent frames
    num = len(ssi_array)
    # initialize the shot_array variable
    framechange_array = [0]
    last_hit = 0
    for i in range (0, num-3):
    
        ssim_ab = ssi_array[i]
        ssim_bc = ssi_array[i+1]
        ssim_cd = ssi_array[i+2]

        firstCheckPass = False
   
        frame_a_index = i + 1
        if (frame_a_index < 0): 
            frame_a_index = 0

        frame_b_index = i + 2
        if (frame_b_index >= num-3):
            frame_b_index = num-3-1

        frame_a = all_frames[frame_a_index]
        frame_b = all_frames[frame_b_index]
        # frame_a = cv2.imread(frames_jpg_path+'frame'+str(frame_a_index)+'.jpg')
        # frame_b = cv2.imread(frames_jpg_path+'frame'+str(frame_b_index)+'.jpg')

        hist1 = []
        color = ('b','g','r')
        for j,col in enumerate(color):
            histr = cv2.calcHist([frame_a],[j],None,[256],[0,256])
            hist1.append(histr)

        hist2 = []
        for j,col in enumerate(color):
            histr = cv2.calcHist([frame_b],[j],None,[256],[0,256])
            hist2.append(histr)

        hist1a = np.asarray(hist1)
        hist2a = np.asarray(hist2)

        average_dist = 0

        hist1a_max = []
        hist2a_max = []
        SimilarColorCheck = False

        for j in range(3):
            dist = cv2.compareHist(hist1a[j], hist2a[j], 0)
            average_dist = average_dist + dist
            max_val = 0

            max_color = 0
            for k in range(len(hist1a[j])):
                if hist1a[j][k][0] > max_val:
                    max_val = hist1a[j][k][0]
                    max_color = k
            hist1a_max.append(max_color)

            max_val = 0
            max_color = 0
            for k in range(len(hist2a[j])):
                if hist2a[j][k][0] > max_val:
                    max_val = hist2a[j][k][0]
                    max_color = k
            hist2a_max.append(max_color)

        CumulativeColorDiffs = 0

        for j in range(3):
            CumulativeColorDiffs += abs(hist1a_max[j] - hist2a_max[j])

        if CumulativeColorDiffs < 20:
            SimilarColorCheck = True

        average_dist = average_dist / 3.0

        ssim_histo_val = min(max((1.0 - ssim_bc/ssim_ab), 0), 1.0) + min(max((1.0 - ssim_bc/ssim_cd), 0), 1.0) + (1.0 - average_dist)

        if (ssim_bc/ssim_ab < 0.6 and ssim_bc/ssim_cd < 0.6):
            if average_dist < 0.95:
                firstCheckPass = True
        elif (ssim_bc/ssim_ab < 0.6 or ssim_bc/ssim_cd < 0.6):
            if average_dist < 0.4:
                firstCheckPass = True
            elif ssim_histo_val > 1.0 and SimilarColorCheck is False:
                firstCheckPass = True
        elif ssim_histo_val > 1.0 and SimilarColorCheck is False:
            firstCheckPass = True
        
        # 0.6 is chosen because a 60% change in similarity works well for a shot change threshold
        if (firstCheckPass is True and i+2-last_hit > 15):
            framechange_array.append(i+2)
            last_hit = i+2


    # USE FOR A 2ND PASS THROUGH SHOTS TO MAKE SURE THEY ARE CORRECT

    new_frame_changes = []

    last_hit = 0

    # for x in range(len(framechange_array)-1):
    #     shots_in_frame = framechange_array[x+1] - framechange_array[x] - 1

    #     for k in range(0, shots_in_frame-10, 10):

    #         i = framechange_array[x] + k
    #         frame_a = cv2.imread(frames_jpg_path+'frame'+str(i)+'.jpg')
    #         frame_b = cv2.imread(frames_jpg_path+'frame'+str(i+10)+'.jpg')

    #         frame_a_bw = cv2.cvtColor(frame_a, cv2.COLOR_BGR2GRAY)
    #         frame_b_bw = cv2.cvtColor(frame_b, cv2.COLOR_BGR2GRAY)
    #         average_dist = ssim(frame_a_bw, frame_b_bw)
    #         #mad = np.sum(np.abs(np.subtract(frame_a_bw, frame_b_bw)))/(frame_a_bw.shape[0])

    #         # hist1 = []
    #         # color = ('b','g','r')
    #         # for j,col in enumerate(color):
    #         #     histr = cv2.calcHist([frame_a],[j],None,[256],[0,256])
    #         #     hist1.append(histr)

    #         # hist2 = []
    #         # for j,col in enumerate(color):
    #         #     histr = cv2.calcHist([frame_b],[j],None,[256],[0,256])
    #         #     hist2.append(histr)

    #         # hist1a = np.asarray(hist1)
    #         # hist2a = np.asarray(hist2)

    #         # average_dist = 0

    #         # for j in range(3):
    #         #     dist = cv2.compareHist(hist1a[j], hist2a[j], 0)
    #         #     average_dist = average_dist + dist

    #         # average_dist = average_dist / 3.0

    #         # average_dist, residual_frame = BlockMatching.main(frames_jpg_path+'frame'+str(i)+'.jpg', frames_jpg_path+'frame'+str(i+10)+'.jpg')

    #         # print(average_dist)

    #         if (average_dist < 0.05 and i - last_hit > 50):
    #             # Split up the frame here
    #             last_hit = i
    #             print(i)
    #             new_frame_changes.append(i+5)


    # framechange_array_copy = framechange_array.copy()

    # for i in range(len(new_frame_changes)):
    #     for k in range(len(framechange_array_copy)):
    #         if (new_frame_changes[i] > framechange_array_copy[k]):
    #             if k == len(framechange_array_copy) - 1 or (new_frame_changes[i] < framechange_array_copy[k+1]):
    #                 framechange_array.insert(k + 1, new_frame_changes[i])
    #                 break
                

    # add the last frame to the array to the end if last frame is more than last shot change
    if num-1 > framechange_array[-1] + 4:
        framechange_array.append(num-1)
    
    return (framechange_array)
from matplotlib import pyplot as plt
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", image)

hist = cv2.calcHist([image], [0], None, [256], [0, 256])

plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)
plt.xlim([0, 256])
plt.show()
cv2.waitKey(0)
Esempio n. 57
0
img_src = cv2.imread('picture/moon_homo.png', 1)

img_gry = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)

#ヒストグラム表示用のイメージを作成
img_histgram = np.zeros([100, 256]).astype('uint8')
rows, cols = img_histgram.shape

#次元ごとの度数分布サイズ
hdims = [256]

#各次元の度数分布の最小値と最大値
hranges = [0, 256]

#変数(入力画像,入力画像の種類(0:グレースケール,0~2:カラー画像でのrgb),マスク画像(画像中の全画素ならNone),ビンの数(全てなら[256]),計測したい画素値の範囲)
histgram = cv2.calcHist([img_gry], [0], None, hdims, hranges)                                           #histgramは[256][1]の配列で,各要素は対応する画素値を持つ画素の数を表す

#グレースケールから最も明るい画素と暗い画素の位置を出力する(min_val,max_val:画素の値、min_loc,max_loc:画素の位置)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(histgram)

for i in range(0, 255):

    v = histgram[i]

    #変数(線を引く画像,開始座標,終了座標,線の色,(線の太さ))
    cv2.line(img_histgram, (i, rows), (i, rows - int(rows * float(v / max_val))), (255, 255, 255))

cv2.imshow('dst', img_histgram)
cv2.waitKey(0)
cv2.destroyAllWindows()
Esempio n. 58
0
def main():
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-v", "--video", help="path to the (optional) video file")
    args = vars(ap.parse_args())

    # grab the reference to the current frame, list of ROI
    # points and whether or not it is ROI selection mode
    global frame, roiPts, inputMode

    # if the video path was not supplied, grab the reference to the
    # camera
    if not args.get("video", False):
        camera = cv2.VideoCapture(0)

    # otherwise, load the video
    else:
        camera = cv2.VideoCapture(args["video"])

    # setup the mouse callback
    cv2.namedWindow("frame")
    cv2.setMouseCallback("frame", selectROI)

    # initialize the termination criteria for cam shift, indicating
    # a maximum of ten iterations or movement by a least one pixel
    # along with the bounding box of the ROI
    termination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
    roiBox = None

    # keep looping over the frames
    while True:
        # grab the current frame
        (grabbed, frame) = camera.read()

        # check to see if we have reached the end of the
        # video
        if not grabbed:
            break

        # if the see if the ROI has been computed
        if roiBox is not None:
            # convert the current frame to the HSV color space
            # and perform mean shift
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            backProj = cv2.calcBackProject([hsv], [0], roiHist, [0, 180], 1)

            # apply cam shift to the back projection, convert the
            # points to a bounding box, and then draw them
            (r, roiBox) = cv2.CamShift(backProj, roiBox, termination)
            pts = np.int0(cv2.boxPoints(r))
            cv2.polylines(frame, [pts], True, (0, 255, 0), 2)

        # show the frame and record if the user presses a key
        cv2.imshow("frame", frame)
        key = cv2.waitKey(1) & 0xFF

        # handle if the 'i' key is pressed, then go into ROI
        # selection mode
        if key == ord("i") and len(roiPts) < 4:
            # indicate that we are in input mode and clone the
            # frame
            inputMode = True
            orig = frame.copy()

            # keep looping until 4 reference ROI points have
            # been selected; press any key to exit ROI selction
            # mode once 4 points have been selected
            while len(roiPts) < 4:
                cv2.imshow("frame", frame)
                cv2.waitKey(0)

            # determine the top-left and bottom-right points
            roiPts = np.array(roiPts)
            s = roiPts.sum(axis=1)
            tl = roiPts[np.argmin(s)]
            br = roiPts[np.argmax(s)]

            # grab the ROI for the bounding box and convert it
            # to the HSV color space
            roi = orig[tl[1]:br[1], tl[0]:br[0]]
            roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
            #roi = cv2.cvtColor(roi, cv2.COLOR_BGR2LAB)

            # compute a HSV histogram for the ROI and store the
            # bounding box
            roiHist = cv2.calcHist([roi], [0], None, [16], [0, 180])
            roiHist = cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)
            roiBox = (tl[0], tl[1], br[0], br[1])

        # if the 'q' key is pressed, stop the loop
        elif key == ord("q"):
            break

    # cleanup the camera and close any open windows
    camera.release()
    cv2.destroyAllWindows()
Esempio n. 59
0
cv2.pyrMeanShiftFiltering(image,30,20,dst,3)
cv2.imshow('img2',dst);
cv2.imwrite('im1.jpg',dst);

med = cv2.medianBlur(dst,5);
img_hsv = cv2.cvtColor(dst,cv2.COLOR_BGR2HSV)
cv2.imshow('img3',img_hsv)
cv2.imwrite('im2.jpg',img_hsv);

k = cv2.waitKey(0);
if(k==27):
    cv2.destroyAllWindows()

color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img_hsv],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.show()

# identify regions
# b = int(med[:][:][0]);
# g = int(med[:][:][1]);
# r = int(med[:][:][2])
#
# h = int(img_hsv[:][:][0])
# s = int(img_hsv[:][:][1])
# v = int(img_hsv[:][:][2])

height,width,channel = dst.shape;
temp = [['a' for x in range(width)] for y in range(height)]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec  1 18:06:14 2018

@author: xsxsz
"""

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('scenery.jpg')
color = ('r', 'g', 'b')
plt.figure(0)
plt.imshow(img)
plt.figure(1)
plt.hist(img.ravel(), 256, [0, 256])
plt.figure(2)
for i, color in enumerate(color):
    hist = cv2.calcHist(images=[img],
                        channels=[i],
                        mask=None,
                        histSize=[256],
                        ranges=[0, 256])
    plt.plot(hist, color)