I am trying to read an excel using python, Excel has two columns name as Product_Name and second is LOGO. product Name as the name suggests contains the Product Name Like Fish ,Laptop whereas Second columns contain the logo of that Product Name.I am trying to save images from the LOGO column with image name as Product Name .Below Code is working fine but Product Name and saved Images are mismatching
import win32com.client # Need pywin32 from pip
from PIL import ImageGrab # Need PIL as well
import os
excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.ActiveWorkbook
wb_folder = workbook.Path
wb_name = workbook.Name
wb_path = os.path.join(wb_folder, wb_name)
print(wb_path)
print("Extracting images from %s" % wb_path)
image_no = 0
for sheet in workbook.Worksheets:
if(sheet.Name == "Ch"):
for shape,r in zip(sheet.Shapes,range(4,200)):
if shape.Name.startswith("Picture"):
image_no += 1
print("---- Image No. %07i ----" % image_no)
print(r)
imagen = sheet.Cells(r,'E').value
filename = sheet.Cells(r,'E').value + ".jpg"
file_path = os.path.join (wb_folder, filename)
print("Saving as %s" % file_path) # Debug output
shape.Copy() # Copies from Excel to Windows clipboard
# Use PIL (python imaging library) to save from Windows clipboard
# to a file
image = ImageGrab.grabclipboard()
print(image)
try:
image.save(file_path,'jpeg')
except AttributeError:
F = open('error.txt','w')
F.write(imagen)
F.close()
Following script extracts all images from Excel file and name them with "Channel name" value:
import re
from PIL import ImageGrab
import win32com.client as win32
FILE = r'C:\Users\user\Desktop\so\53994108\logo.xlsx'
CELLS = [(4, 5, 'F'), (3, 3, 'D')]
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(FILE)
for i, worksheet in enumerate(workbook.Sheets):
row = CELLS[i][0]
while True:
name = worksheet.Cells(row, CELLS[i][1]).Value
if not name:
break
name = re.sub(r'\W+ *', ' ', name)
rng = worksheet.Range('{}{}'.format(CELLS[i][2], row))
rng.CopyPicture(1, 2)
im = ImageGrab.grabclipboard()
im.save('{}.jpg'.format(name))
row += 1
So I've got following images on the end:
Related
Im trying to copy the pixel information of a group of images to a CSV, however when I try the following code, Im unable to create the csv. Is there any other way to copy the pixels to a csv?
from PIL import Image
import numpy as np
import sys
import os
import csv
# default format can be changed as needed
def createFileList(myDir, format='.png'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
for name in files:
if name.endswith(format):
fullName = os.path.join(root, name)
fileList.append(fullName)
return fileList
# load the original image
myFileList = createFileList('/test/surprise')
for file in myFileList:
print(file)
img_file = Image.open(file)
# img_file.show()
# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode
# Make image Greyscale
img_grey = img_file.convert('L')
#img_grey.save('result.png')
#img_grey.show()
# Save Greyscale values
value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0]))
value = value.flatten()
print(value)
with open("imagenes.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(value)
I would like to generate a csv with the pixel information similar to FER2013.csv as can be see in the following image.
The following code is to combine multiple images into one pdf. I am trying to run this code on multiple folder where each folder has several images as result, each folder will has one pdf.
import os
from PIL import Image
from fpdf import FPDF
pdf = FPDF()
sdir = "imageFolder/"
w,h = 0,0
for i in range(1, 100):
fname = sdir + "IMG%.3d.png" % i
if os.path.exists(fname):
if i == 1:
cover = Image.open(fname)
w,h = cover.size
pdf = FPDF(unit = "pt", format = [w,h])
image = fname
pdf.add_page()
pdf.image(image,0,0,w,h)
else:
print("File not found:", fname)
print("processed %d" % i)
pdf.output("output.pdf", "F")
print("done")
I was thinking to create another loop to bring the folder path which will come before the first loop:
For j in range(1 to 70):
folderP=sdir+folder%1
And loop in each folder
Sorry I am still learning python. Any suggestion would be great!
You can use glob to get the paths of all pdfs and add them to a list, then you just iterate through the list and you wouldn't even need to check if they exist:
from glob import glob
sDir = 'imageFolder/'
pdfPaths = []
pdfPaths.extend(glob(f'{sDir}**/*.pdf', recursive=True))
for pdf in pdfPaths:
# do stuff
Hello I am trying to read images from the specified directory and want to write the text line by line (that too i m reading from the text file specified) and saving images(text on that images) into other directory specified. But facing the following error.
Code:
import cv2
import glob
import shutil
import os
import numpy as np #for copying and moving files
font = cv2.FONT_HERSHEY_SIMPLEX
input_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\1\\*.*'
output_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\2\\'
file_name = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\3\\code.txt'
def read_file():
if os.path.isfile(file_name):
rows = []
with open (file_name, mode='r') as file:
for line in file:
rows.append(line.strip())
return rows
else:
raise Exception('file name does not exist')
def images_1(input_path, output_path):
for im in glob.glob(input_path):
image = cv2.imread(im)
if im is None:
raise Exception ("images are not found")
else:
print("printing.....")
i= 0
for i in im:
text= read_file()
img = cv2.putText(image, text ,(100,100), font,4,
(225,225,225),cv2.LINE_AA )
cv2.imwrite(output_path + '\\_img' + str(i) + '_.jpg',
img)
images_1(input_path, output_path)
Error:
TypeError: bad argument type for built-in operation
text in cv2.putText function should be of type string, but is list in your case as read_file() returns a list named rows.
So, replace text in cv2.putText function to str(text) or ''.join(text) or '\n'.join(text), etc.
Code:
img = cv2.putText(image, str(text), (100,100), font, 4, (225,225,225), cv2.LINE_AA)
I'm trying to loop through a list of ~3,000 URLs and create QR codes for them. In one column I have the URLs and in another column I have what I want the QR code file names to be named when output as images.
The problem is the URLs that get converted to QR codes and my file names both come out encased in brackets.
For example:
URL Filename
www.abel.com Abel
Comes out as:
URL in QR Code Filename of QR Code
[www.abel.com] [Abel]
Here's my code so far:
import csv
import qrcode
import pandas as pd
df = pd.read_csv('QR_Python_Test.csv')
i = 1
x = df.iloc[[i]]
print(
x.QR_Code_Name.values)
for i in df.index:
z = df.iloc[[i]]
x = str(z.Link_Short.values)
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
qr.add_data(x)
qr.make(fit=True)
img = qr.make_image()
file_name = str(z.QR_Code_Name.values) + ".png"
print('Saving %s' % file_name)
image_file = open(file_name, "w")
img.save(file_name)
image_file.close()
file.close()
And some sample data:
URL Filename
www.apple.com Apple
www.google.com Google
www.microsoft.com Microsoft
www.linux.org Linux
Thank you for your help,
Me
If your DataFrame contains the correct information, you can use DataFrame.itertuples
also separate the functions
reading the data from the file
generating the qr-code
saving the files
That way, you can test each of these individually
def generate_images(df):
for row in df.itertuples():
yield row.Filename, generate_qr(row.URL)
def generate_qr(url):
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
qr.add_data(url)
qr.make(fit=True)
return qr.make_image()
def save_qr_code(qr_codes):
for filename, qr_code in qr_codes:
filename = filename + '.png'
print('saving to file %s' % (filename,)
with open(filename, 'wb') as file:
qr_code.save(file)
df = pd.read_csv('my_data.csv')
qr_codes = generate_images(df)
save_qr_code(qr_codes)
I'm trying to make a script that resize multiple or a single image based on a data pulled from XML.
My question is if i have multiple images how can I print out a qusetion like "There are more than 1 image do you wish to resize image 2 also?... than maybe " Would you liek to resize image 3 also ?"
My script so far is as follow,the only problem is taht it resizez all the images at start :
import os, glob
import sys
import xml.etree.cElementTree as ET
import re
from PIL import Image
pathNow ='C:\\'
items = []
textPath = []
imgPath = []
attribValue = []
#append system argument to list for later use
for item in sys.argv:
items.append(item)
#change path directory
newPath = pathNow + items[1]
os.chdir(newPath)
#end
#get first agrument for doc ref
for item in items:
docxml = items[2]
#search for file
for file in glob.glob(docxml + ".xml"):
tree = ET.parse(file)
rootFile = tree.getroot()
for rootChild in rootFile.iter('TextElement'):
if "svg" or "pdf" in rootChild.text:
try:
textPath = re.search('svg="(.+?)"', str(rootChild.text)).group(1)
attribValue.append(rootChild.get('elementId'))
imgPath.append(textPath)
except:
continue
for image in imgPath:
new_img_path = image[:-4] + '.png'
new_image = Image.open(new_img_path)
new_size=int(sys.argv[3]), int(sys.argv[4])
try:
new_image.thumbnail(new_size, Image.ANTIALIAS)
new_image.save(new_img_path, 'png')
except IOError:
print("Cannot resize picture '%s'" % new_img_path)
finally:
new_image.close()
print("Done resizeing image: %s " % new_img_path)
Thank you in advance.
Zapo
Change your final loop to:
for idx, image in enumerate(imgPath):
#img resizing goes here
count_remaining = len(imgPath) - (idx+1)
if count_remaining > 0:
print("There are {} images left to resize.".format(count_remaining))
response = input("Resize image #{}? (Y/N)".format(idx+2))
#use `raw_input` in place of `input` for Python 2.7 and below
if response.lower() != "y":
break