2016-05-28 3 views
1

Мне нужно сохранить гистограммы изображений из базы данных, которые впоследствии могут использоваться для сравнения с гистограммой изображения, заданного пользователем. Проблема: как я могу хранить гистограммы & как сравнить гистограммы?Python .. обработка изображений

import numpy as np 
import cv2 
from matplotlib import pyplot as plt 

def thresholded(center, pixels): 
    out = [] 
    for a in pixels: 
     if a >= center: 
      out.append(1) 
     else: 
      out.append(0) 
    return out 

def get_pixel_else_0(l, idx, idy, default=0): 
    try: 
     return l[idx,idy] 
    except IndexError: 
     return default 

img = cv2.imread('006A61.jpg', 0) 
transformed_img = cv2.imread('006A61.jpg', 0) 

for x in range(0, len(img)): 
    for y in range(0, len(img[0])): 
     center  = img[x,y] 
     top_left  = get_pixel_else_0(img, x-1, y-1) 
     top_up  = get_pixel_else_0(img, x, y-1) 
     top_right  = get_pixel_else_0(img, x+1, y-1) 
     right   = get_pixel_else_0(img, x+1, y) 
     left   = get_pixel_else_0(img, x-1, y) 
     bottom_left = get_pixel_else_0(img, x-1, y+1) 
     bottom_right = get_pixel_else_0(img, x+1, y+1) 
     bottom_down = get_pixel_else_0(img, x, y+1) 

     values = thresholded(center, [top_left, top_up, top_right, right, bottom_right, 
             bottom_down, bottom_left, left]) 

     weights = [1, 2, 4, 8, 16, 32, 64, 128] 
     res = 0 
     for a in range(0, len(values)): 
      res += weights[a] * values[a] 

     transformed_img.itemset((x,y), res) 

    #print x 

cv2.imshow('image', img) 
cv2.imshow('thresholded image', transformed_img) 

hist,bins = np.histogram(img.flatten(),256,[0,256]) 

cdf = hist.cumsum() 
cdf_normalized = cdf * hist.max()/ cdf.max() 

plt.plot(cdf_normalized, color = 'b') 
plt.hist(transformed_img.flatten(),256,[0,256], color = 'r') 
plt.xlim([0,256]) 
plt.legend(('cdf','histogram'), loc = 'upper left') 
plt.show() 

cv2.waitKey(0) 
cv2.destroyAllWindows() 
+0

Добро пожаловать в StackOverflow. Название вашего вопроса очень расплывчато; Улучшение этого увеличивает видимость вашего вопроса. Что-то вроде «сохранения и сравнения гистограмм в Python» было бы намного лучше. –

ответ

0

Вы можете использовать снова np.histogram, чтобы получить значение гистограммы в массив, а затем сохранить его в файл с np.save и загрузить его позже с np.load. Сравнение гистограмм тогда легко. что-то вроде np.linalg.norm(hist1 - hist2). см. Ниже (я изменил cv2 до scupy.misc/pyplot для моего удобства).

import numpy as np 
from scipy.misc import imread 
from matplotlib import pyplot as plt 

pic = r"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" 


def thresholded(center_, pixels): 
    out = [] 
    for a_ in pixels: 
     if a_ >= center_: 
      out.append(1) 
     else: 
      out.append(0) 
    return out 


def get_pixel_else_0(l, idx, idy, default=0): 
    try: 
     return l[idx, idy] 
    except IndexError: 
     return default 

img = imread(pic, mode='I') 
transformed_img = imread(pic, mode='I') 

for x in range(0, len(img)): 
    for y in range(0, len(img[0])): 
     center  = img[x, y] 
     top_left  = get_pixel_else_0(img, x-1, y-1) 
     top_up  = get_pixel_else_0(img, x, y-1) 
     top_right  = get_pixel_else_0(img, x+1, y-1) 
     right   = get_pixel_else_0(img, x+1, y) 
     left   = get_pixel_else_0(img, x-1, y) 
     bottom_left = get_pixel_else_0(img, x-1, y+1) 
     bottom_right = get_pixel_else_0(img, x+1, y+1) 
     bottom_down = get_pixel_else_0(img, x, y+1) 

     values = thresholded(center, [top_left, top_up, top_right, right, bottom_right, 
             bottom_down, bottom_left, left]) 

     weights = [1, 2, 4, 8, 16, 32, 64, 128] 
     res = 0 
     for a in range(0, len(values)): 
      res += weights[a] * values[a] 

     transformed_img.itemset((x, y), res) 

    # print x 
plt.figure() 
plt.imshow(img) 
plt.title('image') 
plt.figure() 
plt.imshow(transformed_img) 
plt.title('thresholded image') 

hist, bins = np.histogram(img.flatten(), 256, [0, 256]) 

cdf = hist.cumsum() 
cdf_normalized = cdf * hist.max()/cdf.max() 
plt.figure() 
plt.plot(cdf_normalized, color='b') 
hist_trans, bins_trans = np.histogram(transformed_img.flatten(), 256, [0, 256]) 
plt.bar(bins_trans[:-1], hist_trans, width=np.diff(bins_trans), color='r') 
plt.xlim([0, 256]) 
plt.legend(('cdf', 'histogram'), loc='upper left') 
plt.show() 

file = r'd:\temp\1.npy' 
np.save(file, hist_trans) 

# do something here... 

hist_trans1 = np.load(file) 
print(np.linalg.norm((hist - hist_trans1))) 
Смежные вопросы