Список не может быть умножен на numpy - PullRequest
0 голосов
/ 10 октября 2018

Я работаю над базовой программой распознавания изображений, которая берет данные пикселей, а затем разбивает их с помощью декомпозиции SVD.Я собрал все данные, и единственное, что у меня осталось, это протолкнуть все данные через несколько матричных операций, и это будет сделано.Тем не менее, я продолжаю получать ошибку, которая кажется глупой, учитывая, что я уже манипулировал матрицей, и она перестала работать, когда я нажимаю np.matmul ().Это нарушается, если функция getEigenvalues.Это ошибка, которую я получаю.Заранее спасибо.

Traceback (most recent call last):
  File "C:/Users/Bryson M/Documents/CS 1400/MORE PYTHON/Image Recognition/camera-test/venv/main.py", line 117, in <module>
    main()
  File "C:/Users/Bryson M/Documents/CS 1400/MORE PYTHON/Image Recognition/camera-test/venv/main.py", line 96, in main
    eigenComparisionMatrix = makeEigenVectors(cleanedData) #makes the eigenvectors that will be used to compare against other pictures
  File "C:/Users/Bryson M/Documents/CS 1400/MORE PYTHON/Image Recognition/camera-test/venv/main.py", line 57, in makeEigenVectors
    matrixM = np.matmul(np.transpose(matrix), matrix) #gives really big rank one matrix
TypeError: Object arrays are not currently supported


import cv2
import numpy as np
import time
import matplotlib as plt

def smallestDimensions(imageList):
    smallestColumns = 100000  # gives a very large starting columns and rows
    smallestRows = 100000
    for image in imageList:
        img = cv2.imread(image)  # reads in images one by one.
        rows, columns, channels = img.shape
        if rows < smallestRows:  # if image has a smaller width, then makes that the smallest width.
            smallestRows = rows
        if columns < smallestColumns:
            smallestColumns = columns
    print("rows: ", smallestRows, "columns: ", smallestColumns)
    return smallestRows, smallestColumns

def makePictureMatrixBGR(imageList, maxRows, maxColumns): #makes the numpy array with pixel data
    pictureDataMatrix = []
    for image in imageList: #takes image one at a time
        bluePixelData = []
        greenPixelData = []
        redPixelData = []

        img = cv2.imread(image)  # reads in images one by one.
        rows, columns, channels = img.shape
        startPosX = (columns - maxColumns) // 2  # centers the area of interest in the middle despite differences in pixel count
        startPosY = (rows - maxRows) // 2

        for x in range(startPosX):
            for y in range(startPosY):
                blue, green, red = (img[x + startPosX, y + startPosY])  # makes blue, green, red arrays for each picture
                bluePixelData.append((blue))  # adds pixels values to three seperate lists
                greenPixelData.append((green))
                redPixelData.append((red))

        print("green pixel data: ", greenPixelData)
        pictureDataMatrix.append(bluePixelData) #makes each pixel value list into a line on the main data matrix
        pictureDataMatrix.append(greenPixelData)
        pictureDataMatrix.append(redPixelData)
    return pictureDataMatrix

def muCenteredData(matrix): #centers each set of data relative to its mean.
    for row in range(len(matrix)):
        sum = 0
        for cell in range(len(matrix[row])):
            sum += matrix[row][cell]
        for cell in range(len(matrix[row])):
            matrix[row][cell] -= sum/(len(matrix[row])) #subtracting mu from each value. mu is the mean of each row.
    return matrix

def covarianceCentered(baseDataMatrix):
    pass

def makeEigenVectors(matrix):
    matrixM = np.matmul(np.transpose(matrix), matrix) #gives really big rank one matrix
    uVectors , eigenValues, vVectors = np.linalg.svd(matrixM) #SVD decomposition
    return vVectors[:,[0,1]] #for now, i take only two columns so that i can nicely print out two numbers, x and y, on a graph

def getMatrixValues(testedMatrix, eigenvectorMatrix):
    x,y = np.matmul(eigenvectorMatrix , testedMatrix)
    return x , y


def main():
    imageList = ["C:\\Users\\Bryson M\\Documents\\CS 1400\\MORE PYTHON\\Image Recognition\\camera-test\\venv\\Images\\SpongbobJump.png",
                 "C:\\Users\\Bryson M\\Documents\\CS 1400\\MORE PYTHON\\Image Recognition\\camera-test\\venv\\Images\\SpongebobHug.png",
                 "C:\\Users\\Bryson M\\Documents\\CS 1400\\MORE PYTHON\\Image Recognition\\camera-test\\venv\\Images\\SpongebobJogging.png",
                 "C:\\Users\\Bryson M\\Documents\\CS 1400\\MORE PYTHON\\Image Recognition\\camera-test\\venv\\Images\\SpongbobShowing.png"]
    observedImage = ["C:\\Users\\Bryson M\\Documents\\CS 1400\\MORE PYTHON\\Image Recognition\\camera-test\\venv\\Images\\mario.png"]

    smallestRows, smallestColumns = smallestDimensions(imageList + observedImage) #finds the smallest dimentions out of all the data for clean linalg operations

    pictureDataMatrix = makePictureMatrixBGR(imageList, smallestRows, smallestColumns)
    observedDataMatrix = makePictureMatrixBGR(observedImage, smallestRows, smallestColumns)

    cleanedData = muCenteredData(pictureDataMatrix)#cleans the data for a more consistant value
    cleanedObservedData = muCenteredData(observedDataMatrix)

    eigenComparisionMatrix = makeEigenVectors(cleanedData) #makes the eigenvectors that will be used to compare against other pictures
#find x y points
    finalPoints = []
    for image in range(imageList):
        x,y = getMatrixValues(cleanedData, eigenComparisionMatrix)
        finalPoints.append([x,y])

#plot points
    plt.suptitle("Base pictures plotted")
    plt.scatter(*zip(*finalPoints),'r*') #base points are red stars. https://stackoverflow.com/questions/21519203/plotting-a-list-of-x-y-coordinates-in-python-matplotlib
    plt.show()
    plt.waitforbuttonpress()
    x,y = getMatrixValues(cleanedObservedData, eigenComparisionMatrix)
    plt.scatter(x,y , 'gs') #observed image is representied by a green square
    plt.suptitle("Oberved Point ")
    plt.show()


startTime = time.time()

if __name__ == "__main__":
    main()

print(time.time() - startTime)
...