Ошибка «индексы списка должны быть целыми числами или частями, а не str» для аналогичного сценария поиска изображений - PullRequest
0 голосов
/ 01 апреля 2019

Я слежу за сценарием поиска похожих изображений в базе данных и их идентификации, созданным Moondra: https://www.youtube.com/watch?v=8rcVcH4OTdo.

Я копировал это слово в слово и столкнулся с проблемой, которая говорит, что "индексы списка должны быть целыми числами или кусочками, а не str".

Происходит, когда я запускаю строку:

дубликаты, ds_dict, hash_ds = diff_score_dict_hash (image_files)

У меня также проблема с тем, чтобы он выводил изображения, чтобы я мог видеть, какие из них являются дубликатами. Если есть простой способ показать, какие изображения являются дубликатами, это также будет оценено.

(P.S в основном для Moondra)

Это код (только для необходимого контекста):

import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread, imresize, imshow
import numpy as np
import cv2
import os
import time
from hashlib import md5

IMAGE_DIR = 'c:\\users\\JeffO\\desktop\\Image_Test'
os.chdir(IMAGE_DIR)
os.getcwd()

image_files = os.listdir()
print(len(image_files))

#Gets name of image
image_files[0]

#Gets shape of image
imread(image_files[0]).shape


##Helper functions

#Makes sure image is 3 dimensional

def filter_images(images):
    image_list = []
    for image in images:
        try:
            assert imread(image).shape[2] == 3
            image_list.append(image)
        except AssertionError as e:
            print(e)
        return image_list

#Turning the image into gray scale

def img_gray(image):
    image = imread(image)
    return np.average(image, weights=[0.229, 0.587, 0.114], axis=2)

#Resize the images and flatten
def resize (image, height=30, width= 30):
   row_res= cv2.resize(image, (height, width), interpolation = cv2.INTER_AREA).flatten()
   col_res= cv2.resize(image, (height, width), interpolation = cv2.INTER_AREA).flatten('F')
    return row_res, col_res

#Gradient direction based on intesity

def intensity_diff(row_res, col_res):
    difference_row = np.diff(row_res)
    difference_col = np.diff(col_res)
    difference_row = difference_row > 0
    difference_col = difference_col > 0
     return np.vstack((difference_row, difference_col)).flatten()

##Helper functions end

# Hashes the images 
def file_hash(array):
    return md5(array).hexdigest()

#Takes all the functions and puts it into one big function

def difference_score(image, height = 30, width = 30):
    gray = img_gray(image)
    row_res, col_res = resize(gray, height, width)
    difference = intensity_diff(row_res, col_res)

    return difference

#Creating a dictionary of all the hash values
def difference_score_dict_hash(image_list):
    ds_dict = [] #Holds the keys
    duplicates = [] #Holds the duplicates
    hash_ds = []
    for image in image_list:
        ds = difference_score(image)
        hash_ds.append(ds)
        filehash = md5(ds).hexdigest() #Creates a hash out of dict store
        if filehash not in ds_dict:
        ds_dict[filehash] = image
    else:
        duplicates.append((image, ds_dict[filehash]))

return duplicates, ds_dict, hash_ds

#Finds the duplicates
image_files = filter_images(image_files)
duplicates, ds_dict, hash_ds = difference_score_dict_hash(image_files)

!!!!!!!

Это точная ошибка, которую я получаю:

Файл "", строка 1, в дубликаты, ds_dict, hash_ds = diff_score_dict_hash (image_files)

Файл "", строка 96, в diff_score_dict_hash ds_dict [filehash] = image

TypeError: индексы списка должны быть целыми или кусочками, а не str

...