首页 > 解决方案 > for el in x ->TypeError: 'float' object is not iterable

问题描述

phash.py

import cv2
import numpy as np
import sys
import collections

def flatten(x):
    result = []
    for el in x:
        if isinstance(x, collections.Iterable) and not isinstance(el, str):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

def pHash(imgfile):
    """get image pHash value"""
    #加载并调整图片为32x32灰度图片 Load and resize the image to a 32x32 grayscale image
    img=cv2.imread(imgfile, 0) 
    img=cv2.resize(img,(64,64),interpolation=cv2.INTER_CUBIC)

    #创建二维列表 Create a two-dimensional list
    h, w = img.shape[:2]
    vis0 = np.zeros((h,w), np.float32)
    vis0[:h,:w] = img       #填充数据Data input

    #二维Dct变换Two-dimensional Dct transform
    vis1 = cv2.dct(cv2.dct(vis0))
    #cv.SaveImage('a.jpg',cv.fromarray(vis0)) #保存图片save image
    vis1.resize(32,32)

    #把二维list变成一维list Turn a two-dimensional list into a one-dimensional list
    img_list=flatten(vis1.tolist())

    #计算均值 Calculating the mean
    avg = sum(img_list)*1./len(img_list)
    avg_list = ['0' if i<avg else '1' for i in img_list]

    #得到哈希值 Get the hash value
    return ''.join(['%x' % int(''.join(avg_list[x:x+4]),2) for x in range(0,32*32,4)])
def hammingDist(s1,s2):
    assert len(s1)==len(s2)
    return sum([ch1!=ch2 for ch1,ch2 in zip(s1,s2)])

HASH1=pHash('apple1.jpg')
HASH2=pHash('apple2.jpg')
out_score=1-hammingDist(HASH1,HASH2)*1./(32*34/4)
print (out_score)

all code is above: I want to print the hamming distance between image1 and image2 (after convert to list), but the vis1.tolist() has a 'float' object, it can not iterable. How can I do

标签: python

解决方案


推荐阅读