How to create a CSV file with the pixel values of an image

Asked

Viewed 110 times

0

I’m having trouble getting the data from the pixels of an image and write to a CSV file, follow the current code. The error is in the .writerow, however I cannot identify how to change to work.

import cv2
import numpy as np
import csv

img = cv2.imread('frame22.png',0)

kernel = np.ones((5,5),np.uint8)

erosion = cv2.erode(img,kernel,iterations = 1, borderValue=1)

dilationcomerosion = cv2.dilate(erosion,kernel,iterations = 1, borderValue=-1)


cv2.namedWindow("Input", cv2.WINDOW_NORMAL)

cv2.namedWindow("dilationcomerosion", cv2.WINDOW_NORMAL)

cv2.imshow('Input', img)
cv2.imshow('dilationcomerosion', erosion)

rows, cols = img.shape

with open('mycsv.csv', 'w') as f:

    thewriter = csv.writer(f, delimiter=',')

    for i in range(rows):

        for j in range(cols):

            k = img[i,j]

            thewriter.writerow(k)

cv2.waitKey(0)
  • What mistake you get?

  • The guy could find another way to visualize what was useful by using this code, as I use Pycharm I just use Debug and visualize the variable as an array. Thank you for your attention!

  • In thewriter.writerow(k) I don’t see the variable k in your program. Try to use thewriter.writerow(nome_da_variável) with a variable with the data that will be written to the csv file. But a pixel is an array of arrays, so as you mentioned, it’s best to view it in Pycharm or with an image and graphics viewing library.

1 answer

0

I suggest changing the recording pipeline of the csv file. The method writerow() expects an eternal, but the for is returning a Numpy object.

with open('mycsv.csv', 'w') as f:
    for x in range(rows):
        for y in range(cols):
            pixValue = img[x, y]
            f.write("{0}\n".format(pixValue))

Another simple way to solve, would be to pass an iterable (list) to the method writerow().

Of:

thewriter.writerow(k)

To:

thewriter.writerow([k])
  • Consider including a brief explanation of your solution.

  • 1

    Done. Thank you @Marcellalves.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.