我目前有两个代码。一个在黑色背景上生成50个彩色圆的随机图像,在黑色背景上生成一个彩色矩形的一个图像。大小和颜色各不相同。我当前正在使用Hu矩来查找包含矩形的图像。我遇到的问题是该程序出于某种原因仅适用于.png图片,而不适用于.jpg图片。 opencv读取这些文件的原因有什么区别?甚至可能是jpg图片,由于某些时刻等于零,它破坏了代码,所以当我尝试进行对数转换时,它不起作用。
import glob
import cv2
import math
import os
pictures=(glob.glob("./*.png"))
values=[]
for i in pictures: #goes through the pictures in the folder and calculates their hu moments
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
z,img = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
moments = cv2.HuMoments(cv2.moments(img)).flatten()
adjusted=[]
print(moments)
for j in moments: #log adjusts the moments so that they are easier to read
try:
adjusted.append(-1*math.copysign(1.0,j)*math.log10(abs(j)))
except:
print('')
values.append(moments)
average=[0,0,0,0,0,0,0]
for i in values: #next two for loops find the average of the all of the hu moments
for j in range(7):
average[j]=average[j]+i[j]
for i in range(7):
average[i]=average[i]/51
diff=[]
for i in values: #finds the total difference for each hu moment and the average
total=0
for j in range(7):
total=abs(i[j]-average[j])+total
#print (total)
diff.append(total)
print (diff)
candidate=diff.index(max(diff)) #finds which picture had the highest difference from average
print(diff.index(max(diff)))
print(pictures[candidate])
img = cv2.imread(pictures[candidate]) #opens the image to show the sqaure image
cv2.imshow("sqaure image", img)
cv2.waitKey(0)
因此,如前所述,此代码仅适用于png图片,而不适用于jpg。有人知道为什么是这样吗?另外,如果您想要创建图像的程序,我也可以上传它。