Convert Jpg to Greyscale CSV Using R

convert jpg to greyscale csv using R

There are some formulas for how to do this at this link. The raster package is one approach. THis basically converts the RGB bands to one black and white band (it makes it smaller in size, which I am guessing what you want.)

library(raster)
color.image <- brick("yourjpg.jpg")

# Luminosity method for converting to greyscale
# Find more here http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
color.values <- getValues(color.image)
bw.values <- color.values[,1]*0.21 + color.values[,1]*0.72 + color.values[,1]*0.07

I think the EBImage package can also help for this problem (not on CRAN, install it through source:

source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)

color.image <- readImage("yourjpg.jpg")
bw.image <- channel(color.image,"gray")
writeImage(bw.image,file="bw.png")

How to convert grey scale image to respective pixel values (0-1) in the form of matrix or data frame?

The reason why your greyscale image file loads into R as 3D array rather than a 2D matrix is that its pixel intensities are replicated across RGB color channels. The solution to this is to use the function channel to convert the data to Greyscale representation. This will give you a 2D matrix of pixel intensities in the [0:1] range. You can then use the regular write.csv function to save the image data into a .csv file. You might want to do the transposition to convert from column-major order representation used by R to row-major order.

library("EBImage")

img <- readImage("sample.jpg")
img <- channel(img, "grey")
write.csv(t(img), "sample.csv", row.names = FALSE)

Producing many different hashes of a jpg file with minimal change to picture

You can change the comment part of the file by playing with the file header. A simple way to do that is to use a ready made open source program that allows you to put the comment of your choice, example HLLO repeated 8 times. That should give you 256 bits to play with. You can then determine the place where the HLLO pattern is located in the file using a hex editor. You then load the data in memory and start changing these 32 bytes and calculate the hash each time to get a collision (a hash that matches)

By the time you find a collision, the universe will have ended.

Although in theory doable, it's practically impossible to crack SHA256 in a reasonable amount of time, standard encryption protocols would be over and hackers would be enjoying their time.

Convert csv file having pixel values into images

If you have name in last column then you have to convert without last element data[:-1]. And use last column in filenamename savefig( data[-1] + str(i) + '.jpg' ). Without extension it may not know what type of image to write.

You have to count i for every label separatelly - ie. using dict

i = dict() 
i[label] = 0

# later

i[label] += 1
savefig( label + str(i[label]) + '.jpg'

You can also use PIL/'pillowinstead ofmatplotlib` to write it.

from PIL import Image    

image = Image.fromarray(pixels)
image.save(filename)

import numpy as np
import csv
from PIL import Image

counter = dict()

with open('myfile.csv') as csv_file:
csv_reader = csv.reader(csv_file)

# skip headers
next(csv_reader)

for row in csv.reader(csv_reader):

pixels = row[:-1] # without label
pixels = np.array(pixels, dtype='uint8')
pixels = pixels.reshape((28, 28))
image = Image.fromarray(pixels)

label = row[-1]

if label not in counter:
counter[label] = 0
counter[label] += 1

filename = '{}{}.jpg'.format(label, counter[label])
image.save(filename)

print('saved:', filename)

EDIT: Example which show it with one row of data for those which whan to test it without downloading csv file.

import numpy as np
import csv
from PIL import Image

counter = dict()

row = [
255, 0, 0, 0, 0, 0, 255,
0, 255, 255, 255, 255, 255, 0,
0, 255, 0, 255, 0, 255, 0,
0, 255, 255, 255, 255, 255, 0,
0, 255, 0, 0, 0, 255, 0,
0, 255, 255, 255, 255, 255, 0,
255, 0, 0, 0, 0, 0, 255,
'face'
]

pixels = row[:-1]

pixels = np.array(pixels, dtype='uint8')
pixels = pixels.reshape((7, 7))
image = Image.fromarray(pixels)

label = row[-1]

if label not in counter:
counter[label] = 0
counter[label] += 1

filename = '{}{}.png'.format(label, counter[label])

image.save(filename)

print('saved:', filename)

Result: face1.png:

Sample Image


EDIT: I checked your csv file and pixels are not integer values but float (positive, negative) values so you can't use uint8. It has to be float.

pixels = np.array(pixels, dtype='float')

You could convert image to RGB or grayscale L to save it

image = image.convert('RGB')
image = image.convert('L')

but it seems it has problem to convert negative values.

Using

plt.imsave(filename, pixels)

I get expected result


import numpy as np
import csv
from PIL import Image
import matplotlib.pyplot as plt

counter = dict()

with open('gen_image_wgan.csv') as csv_file:
csv_reader = csv.reader(csv_file)

# skip headers
next(csv_reader)

for row in csv_reader:

pixels = row[:-1] # without label
pixels = np.array(pixels, dtype='float')
pixels = pixels.reshape((28, 28))

label = row[-1]

if label not in counter:
counter[label] = 0
counter[label] += 1

filename = '{}{}.png'.format(label, counter[label])
plt.imsave(filename, pixels)

print('saved:', filename)

I want to convert an image to greyscale 'by hand' using numpy functions

What I was looking for was something like this:

def grey_scale(img):
"""Converts an image to grayscale"""
avg = np.mean(img, axis=2) # reads the RGB values and gets the average
grey_img = np.dstack([avg, avg, avg]).astype('uint8') # stacks the R, G and B channels
return grey_img

Converting an image to grayscale using numpy

Here is a working code:

def grayConversion(image):
grayValue = 0.07 * image[:,:,2] + 0.72 * image[:,:,1] + 0.21 * image[:,:,0]
gray_img = grayValue.astype(np.uint8)
return gray_img

orig = cv2.imread(r'C:\Users\Jackson\Desktop\drum.png', 1)
g = grayConversion(orig)

cv2.imshow("Original", orig)
cv2.imshow("GrayScale", g)
cv2.waitKey(0)
cv2.destroyAllWindows()


Related Topics



Leave a reply



Submit