def is_similar(image1, image2): "Compares two images" logger.debug("First image: %s, Second image: %s", image1, image2) image1 = cv2.imread(image1) image2 = cv2.imread(image2) first_image_hist = cv2.calcHist([image1], [0], None, [256], [0, 256]) second_image_hist = cv2.calcHist([image2], [0], None, [256], [0, 256]) # img_hist_diff = cv2.compareHist( # first_image_hist, second_image_hist, # cv2.HISTCMP_BHATTACHARYYA # ) img_template_probability_match = cv2.matchTemplate( first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0] img_template_probability_match *= 100 similar = bool(img_template_probability_match >= TRESHOLD_PERCANTAGE) log_level = logging.WARNING if similar else logging.INFO logger.log(log_level, "Similarity: %s", str(img_template_probability_match)) return similar
def on_mouse(event, x, y, flags, img): global point1, point2 img2 = img.copy() if event == cv2.EVENT_LBUTTONDOWN: # 左键点击 point1 = (x, y) cv2.circle(img2, point1, 10, (0, 255, 0), 5) cv2.imshow('image', img2) # 按住左键拖曳 elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): cv2.rectangle(img2, point1, (x, y), (255, 0, 0), 5) cv2.imshow('image', img2) elif event == cv2.EVENT_LBUTTONUP: # 左键释放 point2 = (x, y) cv2.rectangle(img2, point1, point2, (0, 0, 255), 5) cv2.imshow('image', img2) min_x = min(point1[0], point2[0]) min_y = min(point1[1], point2[1]) width = abs(point1[0] - point2[0]) height = abs(point1[1] - point2[1]) cut_img = img[min_y:min_y+height, min_x:min_x+width] # cv2.imwrite('500.jpg', cut_img) # 显示RGB三个通道的图像 # 方法一:显示在一张图上 # 按R、G、B三个通道分别计算颜色直方图 b_hist = cv2.calcHist([cut_img], [0], None, [256], [0, 256]) g_hist = cv2.calcHist([cut_img], [1], None, [256], [0, 256]) r_hist = cv2.calcHist([cut_img], [2], None, [256], [0, 256]) # 显示3个通道的颜色直方图 plt.plot(b_hist, label='B', color='blue') plt.plot(g_hist, label='G', color='green') plt.plot(r_hist, label='R', color='red') plt.legend(loc='best') plt.xlim([0, 256]) plt.show()
def hist_compare(image1, image2): size = image1.shape[:2] image1 = cv.resize(image1, size) image2 = cv.resize(image2, size) image1 = cv.cvtColor(image1, cv.COLOR_BGR2GRAY) image2 = cv.cvtColor(image2, cv.COLOR_BGR2GRAY) # image1 = cv.equalizeHist(image1) # image2 = cv.equalizeHist(image2) hist1 = cv.calcHist([image1], [0], None, [256], [0, 256]) hist2 = cv.calcHist([image2], [0], None, [256], [0, 256]) match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA) match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL) match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR) # 巴氏距离越小越相似,相关性越大越相似,卡方越大越不相似 print("巴氏距离", match1) print("相关性", match2) print("卡方", match3) # 直方图绘制 # 2-2-1 plt.subplot(221) plt.imshow(image1, cmap=plt.cm.gray) # 2-2-3 plt.subplot(223) plt.imshow(image2, cmap=plt.cm.gray) # 2-2-2 plt.subplot(222) plt.plot(hist1) # 线 # 2-2-4 plt.subplot(224) plt.plot(hist2) # 线 plt.show()
def _extract_rgb_histogram(image_path): image = cv2.imread(image_path) b_histogram = cv2.calcHist([image], [0], None, [256], [0, 256]) g_histogram = cv2.calcHist([image], [1], None, [256], [0, 256]) r_histogram = cv2.calcHist([image], [2], None, [256], [0, 256]) return np.median(r_histogram.flatten()), np.median(g_histogram.flatten()), np.median(b_histogram.flatten())
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 = numpy.extract(a > 0, b) gData = numpy.extract(a > 0, g) rData = numpy.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 = numpy.extract(a > 0, b) gData = numpy.extract(a > 0, g) rData = numpy.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()
def main_color_moment(self,img,see_make=False)->list: xmin,xmax,ymin,ymax,mat=self.mini_img(img) img=img[ymin:ymax,xmin:xmax] img1=img.copy() img1=cv.cvtColor(img,cv.COLOR_BGR2HSV) img1[mat!=255]=[0,0,0] # B,G,R=cv.split(img1) # #hhh=img.copy() # R[R!=0]=0 # G[G!=0]=0 # hhh=cv.merge([B,G,R]) if see_make: cv.imshow('rrr',mat) cv.imshow('ooo',img) cv.imshow('ppp',img1) #cv.imshow('yyy',hhh) #cv.imshow('uuu',mmm) cv.waitKey(0) cv.destroyAllWindows() hist1 = cv.calcHist([img1],[0], None, [15], [1.0,255.0]) #hist2 = cv.calcHist([img1],[1], None, [3], [1.0,255.0]) hist3 = cv.calcHist([img1],[2], None, [5], [1.0,255.0]) #print(hist6) hist1=hist1/np.sum(hist1) #hist2=hist2/np.sum(hist2) hist3=hist3/np.sum(hist3) hist=np.concatenate((hist1,hist3),axis=0) return hist,mat,(xmin,xmax,ymin,ymax)
def _extract_hsv_histogram(image_path): image = cv2.imread(image_path) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) h_histogram = cv2.calcHist([hsv], [0], None, [256], [0, 256]) s_histogram = cv2.calcHist([hsv], [1], None, [256], [0, 256]) v_histogram = cv2.calcHist([hsv], [2], None, [256], [0, 256]) return np.median(h_histogram.flatten()), np.median(s_histogram.flatten()), np.median(v_histogram.flatten())
def compare(img1, img2): """直方图比较两张图片是否相同""" # 获取图片灰度值分布直方图 hist1 = cv2.calcHist([img1], [0], None, [256], [0, 255]) hist2 = cv2.calcHist([img2], [0], None, [256], [0, 255]) if (hist1 == hist2).all(): return True else: return False
def get_HSV_hist(self, img): hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) t = cv2.calcHist([hsv], [0], None, [180], [0, 180]) hist_H = t / np.sum(t) t = cv2.calcHist([hsv], [1], None, [256], [0, 255]) hist_S = t / np.sum(t) t = cv2.calcHist([hsv], [2], None, [256], [0, 255]) hist_V = t / np.sum(t) return hist_H, hist_S, hist_V
def calculate(image1,image2): hist1 = cv2.calcHist([image1],[0],None,[256],[0.0,255.0]) hist2 = cv2.calcHist([image2],[0],None,[256],[0.0,255.0]) # 计算直方图的重合度 degree = 0 for i in range(len(hist1)): if hist1[i] != hist2[i]: degree = degree + (1 - abs(hist1[i]-hist2[i])/max(hist1[i],hist2[i])) else: degree = degree + 1 degree = degree/len(hist1) return degree
def hist_diff(img_1, img_2): """ Calculates distance between images based on the distance between their histograms. Example found at: https://www.pyimagesearch.com/2014/07/14/3-ways-compare-histograms-using-opencv-python/ """ hist_1 = cv2.calcHist([img_1], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) hist_1 = cv2.normalize(hist_1, hist_1).flatten() hist_2 = cv2.calcHist([img_2], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256]) hist_2 = cv2.normalize(hist_2, hist_2).flatten() return cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_BHATTACHARYYA)
def OTSU(img, sta, fin): hist = cv2.calcHist([img], [0], None, [fin - sta], [sta, fin]) hist_norm = hist.ravel() / hist.max() Q = hist_norm.cumsum() bins = np.arange(fin - sta) fn_min = np.inf thresh = -1 for i in range(1, fin - sta): p1, p2 = np.hsplit(hist_norm, [i]) # probabilities q1, q2 = Q[i], Q[fin - sta - 1] - Q[i] # cum sum of classes b1, b2 = np.hsplit(bins, [i]) # weights # finding means and variances m1, m2 = np.sum(p1 * b1) / q1, np.sum(p2 * b2) / q2 v1, v2 = np.sum(((b1 - m1)**2) * p1) / q1, np.sum( ((b2 - m2)**2) * p2) / q2 # calculates the minimization function fn = v1 * q1 + v2 * q2 if fn < fn_min: fn_min = fn thresh = i thresh += (sta - 1) return thresh
def image_hist(image): #BGR直方图 color = ('blue', 'green', 'red') for i, color in enumerate(color): hist = cv.calcHist([image], [i], None, [256], [0, 256]) plt.plot(hist, color=color) plt.xlim([0, 256]) plt.show()
def DynamicHist(src, winname, section=[0, 256], removeInZero=False, displaySize=(480, 640)): hist = cv2.calcHist([src], [0], None, [section[1] - section[0]], section) hist = hist[:, 0] if removeInZero: hist[0] = 0 binWidth = int(displaySize[1] / hist.shape[0]) k = np.max(hist) / displaySize[0] hist = hist / k black = np.zeros((displaySize[0], hist.shape[0] * binWidth), np.uint8) i = 0 j = 0 for x in np.nditer(hist): j += binWidth black[:int(x), i:j] = 200 i += binWidth p = int(displaySize[0] / 20) scale = np.arange(0, black.shape[1], 50 * binWidth) black[-p:, scale] = 0XFF black = cv2.flip(black, 0) cv2.imshow(winname, black)
def getImgHist256Img(img): chn = getImagChannel(img) hist256Imgs = [] for i in range(chn): hist = cv2.calcHist([img], [i], None, [256], [0, 256]) hist256Imgs.append(getHist256ImgFromHist(hist)) return hist256Imgs
def create_mpl_histogram_color(img, order=('r', 'g', 'b')): """create mpl histogram from the supplied image. this can deal with bgr, or rgb images. :param img: the loaded image :type img: cv2 image :param order: the channel ordering, defaults to ('r', 'g', 'b') :type order: tuple, optional :return: the computed histogram :rtype: mpl plot """ plt.figure() plt.title("'Flattened' Color Histogram") plt.xlabel("Bins") plt.ylabel("# of Pixels") chans = cv2.split(img) # loop over the image channels for (chan, color) in zip(chans, order): hist = cv2.calcHist([chan], [0], None, [256], [0, 256]) plt.plot(hist, color=color) plt.xlim([0, 256]) return plt
def OTSU_Threshold(img,sta,fin): hist = cv2.calcHist([img],[0],None,[fin-sta],[sta,fin]) hist=hist[:,0] total = np.sum(hist) current_max, threshold = 0, 0 sumF, sumB = 0, 0 sumT = np.inner(hist,np.arange(0,fin-sta)) weightB, weightF = 0, 0 varBetween, meanB, meanF = 0, 0, 0 for i in range(0,fin-sta): weightB += hist[i] weightF = total - weightB if weightF == 0: break sumB += i*hist[i] sumF = sumT - sumB meanB = sumB/weightB meanF = sumF/weightF varBetween = weightB * weightF varBetween *= (meanB-meanF)*(meanB-meanF) if varBetween > current_max: current_max = varBetween threshold = i threshold+= sta+1 return threshold
def otsu(img): hist = cv2.calcHist([img], [0], None, [256], [0, 256]) hist_norm = hist.ravel() / hist.max() Q = hist_norm.cumsum() bins = np.arange(256) fn_min = np.inf thresh = -1 for i in range(1, 256): p1, p2 = np.hsplit(hist_norm, [i]) # probabilities q1, q2 = Q[i], Q[255] - Q[i] # cum sum of classes b1, b2 = np.hsplit(bins, [i]) # weights # finding means and variances m1, m2 = np.sum(p1 * b1) / q1, np.sum(p2 * b2) / q2 v1, v2 = np.sum(((b1 - m1) ** 2) * p1) / q1, np.sum(((b2 - m2) ** 2) * p2) / q2 # calculates the minimization function fn = v1 * q1 + v2 * q2 if fn < fn_min: fn_min = fn thresh = i final_img = img.copy() print(thresh) final_img[img > thresh] = 255 final_img[img < thresh] = 0 return final_img
def image_hist_demo(image): color = {"blue", "green", "red"} # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。 for i, color in enumerate(color): hist = cv.calcHist([image], [i], None, [256], [0, 256]) plt.plot(hist, color=color) # 线 plt.show()
def show_gray_histogram(self): numbins = 256 ranges = [0.0, 255.0] width = 256 height = 256 bytes_per_line = 3 * width hist_image = np.zeros([height, width, 3], np.uint8) # hist_image = np.zeros((256,256,3)) #创建用于绘制直方图的全0图像 bins = np.arange(numbins).reshape(numbins, 1) # 直方图中各bin的顶点位置 color = [(255, 0, 0)] # BGR三种颜色 for ch, col in enumerate(color): origin_hist = cv2.calcHist([self.gray_image], [ch], None, [numbins], ranges) cv2.normalize(origin_hist, origin_hist, 0, 255 * 0.9, cv2.NORM_MINMAX) hist = np.int32(np.around(origin_hist)) pts = np.column_stack((bins, hist)) cv2.polylines(hist_image, [pts], False, col) # print(type(hist_image.data)) hist_image = np.flipud(hist_image) # cv2.imshow("histogram", hist_image) demo_utils.show_cvimage_to_label(hist_image, self.gray_histogram_label)
def hist2d_demo(image): hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV) hist = cv.calcHist([hsv],[0,1],None,[180,256],[0,180,0,256]) #cv.imshow("2d",hist) plt.imshow(hist,interpolation='nearest') plt.title("2D") plt.show()
def show_histogram(self): # hist = cv2.calcHist([self.image], # [0], #使用的通道 # None, #没有使用mask # [256], #HistSize # [0.0,255.0]) b, g, r = cv2.split(self.image) numbins = 256 ranges = [0.0, 256.0] b_hist = cv2.calcHist([b], [0], None, [numbins], ranges) g_hist = cv2.calcHist([g], [0], None, [numbins], ranges) r_hist = cv2.calcHist([r], [0], None, [numbins], ranges) print(b_hist.shape) width = 256 height = 256 hist_image = np.zeros([height, width, 3], np.uint8) cv2.normalize(b_hist, b_hist, 0, height * 0.9, cv2.NORM_MINMAX) cv2.normalize(g_hist, g_hist, 0, height * 0.9, cv2.NORM_MINMAX) cv2.normalize(r_hist, r_hist, 0, height * 0.9, cv2.NORM_MINMAX) for i in range(1, numbins, 1): cv2.line(hist_image, (i - 1, height - np.int32(np.around(b_hist[i - 1][0]))), (i, height - np.int32(np.around(b_hist[i][0]))), (255, 0, 0) ) cv2.line(hist_image, (i - 1, height - np.int32(np.around(g_hist[i - 1][0]))), (i, height - np.int32(np.around(g_hist[i][0]))), (0, 255, 0) ) cv2.line(hist_image, (i - 1, height - np.int32(np.around(r_hist[i - 1][0]))), (i, height - np.int32(np.around(r_hist[i][0]))), (0, 0, 255) ) # cv2.imshow("Histogram", hist_image) demo_utils.show_cvimage_to_label(hist_image, self.histogram_label) self.show_histogram2()
def crear_histograma_img(path): norm = np.empty(256) img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) hist = cv2.calcHist([img], [0], None, [256], [0, 256]) h, w = img.shape for i in range(256): norm[i] = hist[i][0] / (h * w) return norm
def plotColorHist(file): img = cv2.imread(file) 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()
def extractColorHistogramFeatures(url, mask_center): img = getImage_cv2(url, 4) if (mask_center): mask = np.zeros(img.shape[:2], np.uint8) mask[100:(img.shape[0]-100), 100:(img.shape[1]-100)] = 255 img = cv2.bitwise_and(img,img,mask = mask) hist_red = cv2.calcHist([img],[2],None,[256],[0,256]) hist_blue = cv2.calcHist([img],[1],None,[256],[0,256]) hist_green = cv2.calcHist([img],[0],None,[256],[0,256]) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) hist_gray = cv2.calcHist([img_gray],[0],None,[256],[0,256]) return hist_red, hist_blue, hist_green, hist_gray
def calc_hist(gray): hist = cv2.calcHist([gray], channels=[0], mask=None, histSize=[256], ranges=[0, 255])[:, 0] hist /= (gray.shape[0] * gray.shape[1]) hist[:5] = 0 return hist
def imageBGR2FlatHist(image, bins=(8, 8, 8)): hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hist = cv2.calcHist([hsv], [0, 1, 2], None, bins, [0, 180, 0, 256, 0, 256]) if imutils.is_cv2(): hist = cv2.normalize(hist) else: cv2.normalize(hist, hist) return hist.flatten()
def calcAndDrawHist(image, color): hist = cv2.calcHist([image], [0], None, [256], [0.0, 255.0]) minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist) histImg = np.zeros([256, 256, 3], np.uint8) hpt = int(0.9 * 256) for h in range(256): intensity = int(hist[h]*hpt/maxVal) cv2.line(histImg, (h, 256), (h, 256-intensity), color) return histImg
def histogram(ImgNo, defThr=127): img1 = cv2.imread(impDef.select_img(ImgNo)) img2 = cv2.imread(impDef.select_img(ImgNo)) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #OpenCV 함수를 이용해 히스토그램 구하기 hist1 = cv2.calcHist([img1], [0], None, [256], [0, 256]) # cv2.calcHist(img, channel, mask, histSize, range) # 이미지 히스토그램을 찾아서 Numpy배열로 리턴 # img : 히스토그램을 찾을 이미지, 인자는 반드시 []로 둘러싸야 함 # Channel : grayscal의 경우 [0]을 입력, 컬러이미지의 경우 B,G,R에 대한 [0],[1],[2]를 입력 # mask : 이미지 전체의 히스토그램을 구할경우 None, 특정영역을 구할 경우 이 영역에 해당하는 mask값을 입력 # histSize : BIN 개수, 인자는 []로 둘러싸야 함. # range : 픽셀값 범위, 보통[0, 256] # 히스토그램의 구하기 위해 가장 성능좋은 함수는 cv2.calcHist() 함수..... #numpy를 이용해 히스토그램 구하기 hist2, bins = np.histogram(img1.ravel(), 256, [0, 256]) # np.histogram # 이미지에서 구한 히스토그램과 BIN의 개수를 리턴 # 1-D 히스토그램의 경우 Numpy가 빠름 hist3 = np.bincount(img1.ravel(), minlength=256) # np.bincount() # Grayscale의 경우 np.historam()보다 약 10배 정도 빠르게 결과를 리턴. # numpy.ravel() : numpy배열을 1차원으로 바꿔주는 함수 # matplotlib으로 히스토그램 그리기 plt.hist(img1.ravel(), 256, [0, 256]) # plt.hist() 하스토그램을 구하지 않고 바로 그림. # 두번째 인자가 BIN의 개수 이 값을 16으로 바꿔주면 BIN의 개수가 16인 히스토그램이 그려짐. # 컬러이미지 히스토그램 그리기 color = ('b', 'g', 'r') for i, col in enumerate(color): hist = cv2.calcHist([img2], [i], None, [256], [0, 256]) plt.plot(hist, color=col) plt.xlim([0, 256]) # 가로축을 0 ~ 256까지로 제한 plt.show()
def histograma(img): # Muestra el histograma de la imagen color = ('r', 'g', 'b') for i, c in enumerate(color): hist = cv2.calcHist([img], [0], None, [256], [0, 256]) plt.plot(hist, color='gray') plt.xlim([0, 256]) plt.show() cv2.destroyAllWindows()