Export Photoshop swatch sheet to a document - colors

I need to export a my Photoshop swatches to a document with RGB, HSB, HEX values and the name of the swatch and maybe the colour patch too. Is there any tool which can export swatches to this kind of a document?

Would not be difficult to script but I don't know of any existing tools. To script it, look into xtools to access the color swatches themselves: http://ps-scripts.sourceforge.net/xtools.html

The following is a limited (no support for lab, hsb or spot color at the moment) python aco -> text dumper. File name needs to be changed to test.aco or change the file name in code
#!/usr/bin/python
# -*- coding: utf-8 -*-
# quick script no warranties whatsoever
import struct
class ColorSwatch():
def __init__(self, fp):
self.rawdata = struct.unpack(">5H",fp.read(10))
namelen, = struct.unpack(">I",fp.read(4))
cp = fp.read(2*namelen)
self.name = cp[0:-2].decode('utf-16-be')
self.typename = self.colorTypeName()
def colorTypeName(self):
try:
return {0:"RGB", 1:"HSB",
2:"CMYK",7:"Lab",
8:"Grayscale"}[self.rawdata[0]]
except IndexError:
print self.rawdata[0]
def __strCMYK(self):
rgb8bit = map(lambda a: (65535 - a)/655.35, self.rawdata[1:])
return "{name} ({typename}): {0}% {1}% {2}% {3}%".format(*rgb8bit,**self.__dict__)
def __strRGB(self):
rgb8bit = map(lambda a: a/256,self.rawdata[1:4])
return "{name} ({typename}): #{0:x}{1:x}{2:x}".format(*rgb8bit,**self.__dict__)
def __strGrayscale(self):
gray = self.rawdata[1]/100.
return "{name} ({typename}): {0}%".format(gray,**self.__dict__)
def __str__(self):
return {0: self.__strRGB, 1:"HSB",
2:self.__strCMYK,7:"Lab",
8:self.__strGrayscale}[self.rawdata[0]]()
with open("test.aco", "rb") as acoFile:
#skip ver 1 file
head = acoFile.read(2)
ver, = struct.unpack(">H",head)
if (ver != 1):
raise TypeError("Probably not a adobe aco file")
count = acoFile.read(2)
cnt, = struct.unpack(">H",count)
acoFile.seek(cnt*10,1)
#read ver2 file
head = acoFile.read(2)
ver, = struct.unpack(">H",head)
if (ver != 2):
raise TypeError("Probably not a adobe aco file")
count = acoFile.read(2)
count, = struct.unpack(">H",count)
for _ in range(count):
swatch = ColorSwatch(acoFile)
print str(swatch)
This question was also posted on Graphic Design Stack Exchange and this is the original answer

https://github.com/czebe/node-swatch-names
This node tool exports your Swatches to SCSS/JS. You can also use it right in node to accomplish transformations and then write it back to an .aco file.

Related

Reading a ini (text) file in Python 3 and use the data to print strings on the screen independently from the text file encode format

in these days I asked a couple of questions related to string encode and file encode in Python but the real problem is harder then I supposed to be and now I have a clearer understanding of the problem.
Windows encoded text files in different formats depending by the language or the language group. So, I would be able to read a ini (text file) encoded in different formats because some keys contain strings that I need to display on forms and menues on the screen.
So I would like to write something (that has to work with any text file and encode format) similar to this code example:
from configparser import ConfigParser
import magic
def detect(iniFileName):
return magic.Magic(mime_encoding=True).from_file(iniFileName)
#---------------------------------------------------------------------------
encoding = detect('config.ini')
ini = ConfigParser()
ini.read('config.ini', encoding)
title = ini.get('USERENTRY-FORM', 'TITLE')
'''
then title is passed to the tk form
'''
UserEntryForm.setTitle(title)
if _DEBUG == True:
print("USERENTRY-FORM title=",title)
This is the new solution that seems to work better because recognizes better the encode format, AIniParser is a wrapper class arund ConfigParser.
from chardet import detect
def chardetPrint(filename):
text = open(filename, 'rb').read()
print(filename,": ",detect(text))
#---------------------------------------------------------------------------
def chardet(filename):
text = open(filename, 'rb').read()
print(filename,": ",detect(text)['encoding']) # only for test
return detect(text)['encoding']
if __name__ == '__main__':
from ainiparser import AIniParser
def testIniRead(filename, section, key):
with open(filename, "rb") as f:
line = f.readline()
print("line 1: ", line)
encode = chardet(filename)
ini = AIniParser(filename, encoding=encode)
ini._open()
text = ini.getString(section, key)
print(text)
def main():
testIniRead("../cdata/config-cro-16.ini", "CGUIINTF", "game-turn-text")
testIniRead("../bat/output-lva-16/idata/config-lva-16.ini", "CGUIINTF", "game-turn-text")
testIniRead("../idata/config-lva-16.ini", "CGUIINTF", "game-turn-text")
testIniRead("../idata/domande.ini", "D2", "B")
#---------------------------------------------------------------------------
main()
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
This solution seems recognizes better how files are encoded but I am still testing it.

How to structure my own Python signal processing module?

I want to take my Python (currently Version 3.9.7) programming skills to a next level. Up to now I just wrote some small scripts for myself, that no one hat to review or reuse. Now, I want to write code that can be considered as "clean" and can be reused by others. For this purpose, I am writing my own signal processing module with which I can generate high- and lowpassfilters in order to filter signals. I have no experience with structuring packages / modules, so I have some questions regarding code structure.
Up to now, I have a class sim_lowpass:
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 22 10:37:19 2022
#author: ilja
"""
from matplotlib import pyplot as plt
import math
class sim_lowpass:
""" Lowpass Simulation Class """
def __init__(self, cutoff: int, order: int, fs: int) -> None:
self.fs = fs
self.nyq = int(0.5 * fs)
self.cutoff = cutoff
self.order = order
def _transfer_func(self,f: float) -> float:
""" Transfer function in the z-domain """
if self.order == 1:
return 1/(1+(f/(2*math.pi*self.cutoff)))
def transfer_func(self) -> list[float]:
""" Transfer function in the z-domain """
if self.order == 1:
# f = np.linspace(self.df, self.nyq, self.N/2)
f = list(range(int(self.nyq)))
return [self._transfer_func(i) for i in f]
def propagate(self, x_hat):
filtered = [i*j for i,j in zip(x_hat, self.impulse_response())]
return filtered
def bode_plot(self, tr_func: list[float]) -> None:
fig, (ax1, ax2) = plt.subplots(2, 1, constrained_layout=True,
figsize = (8,5))
ax1.plot(list(range(self.nyq)), tr_func)
#ax1.set_title('Magnitude')
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_ylabel('Magnitude (dB)')
ax1.grid(True)
# ax2.plot(list(range(self.nyq)), tr_func) # TODO
# ax2.set_title('Phase')
ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.set_xlabel('Frequency (Hz)')
ax2.set_ylabel('Phase (deg)')
ax2.grid(True)
fig.suptitle('Bode Plot', fontsize=16)
def main() -> None:
# define filter params
cutoff = 100
order = 1
fs = 4e6
# create filter
lp = sim_lowpass(cutoff, order, fs)
tf = lp.transfer_func()
lp.bode_plot(tf)
if __name__ == '__main__':
main()
Questions:
First of all: Is the code up to now well structured (in terms of scalability, testability, ... what else is there?)
Second: Now I want to create the class sim_lowpass. How do I continue without copy-pasting the parts I can reuse from the highpass class?
Third: Where do I place this file (and what would be a meaningful name) inside the package hierarchy?
Last but not least: Any other tips for improvement?
I usually get inspiration for code-structure from real projects. For example, since you are using matplotlib, their github could be a place to start: https://github.com/matplotlib/matplotlib/tree/main/lib/matplotlib

od.download() == None but it's not empty | Exception handling Opendatasets

Update: turns out od.download() returns None by design.
What might be better than a None check for od.download() "failure"?
I am downloading a .zip file using opendatasets lib.
In iris_scans(); line print(download), without the if-statement prints None.
However, at invocation scans = iris_scans() data is returned and subsequent prints can display data successfully.
The purpose of the if-statement is for "Graceful error handling".
Note: I've used an if-statement instead of try-except as there are many possibilities why download == None (e.g. dead link, connection interrupt etc.)
pip3 install opendatasets
import opendatasets as od
import zipfile
import os
import shutil
from PIL import Image
import numpy as np
def iris_scans():
download = od.download('http://www.mae.cuhk.edu.hk/~cvl/iris_database/iris_database.zip')
"""
if download == None:
print('Iris Scans - Link could not be established')
return [[]*1778]
"""
print(download)
path_extract = 'iris_database/'
with zipfile.ZipFile('iris_database.zip', 'r') as zip_ref:
zip_ref.extractall(path_extract)
os.remove(path_extract + 'readme.txt')
filenames = os.listdir(path_extract)
scans = []
for f in filenames:
img = Image.open(path_extract + f)
#print("IMG", img)
matrix = np.array(img)
#print("MATRIX", matrix)
scans.append(matrix)
shutil.rmtree(path_extract)
os.remove(path_extract[:-1] + '.zip')
# Data Augmentation
scans_90 = [np.rot90(s) for s in scans]
scans_180 = [np.rot90(s) for s in scans_90]
scans_270 = [np.rot90(s) for s in scans_180]
scans_flip = [np.flip(s) for s in scans]
scans_flip_90 = [np.rot90(s) for s in scans_flip]
scans_flip_180 = [np.rot90(s) for s in scans_flip_90]
scans_flip_270 = [np.rot90(s) for s in scans_flip_180]
scans += scans_90
scans += scans_180
scans += scans_270
scans += scans_flip_90
scans += scans_flip_180
scans += scans_flip_270
return scans
scans = iris_scans()
print(scans[0])
print(len(scans))
The original question was a road-block on the path of implementing some form of Exception Handling for the download.
od.download() == None by design; so an alternative to if download == None needed to be made.
As pointed out and assisted by #Henry; the below Try-except incorporates all exceptions found in the Github source.
...
import urllib
def iris_scans():
try:
download = od.download('http://www.dgcdgyugcwyugyugcasc.com/wqduiuwqdwq') # BROKEN
...
return scans
except (urllib.error.URLError, IOError, RuntimeError) as e:
print('Iris Scans - failed')
return [[]*1778]
Iris Scans - failed
[]
1
Top answer to this post demos many exceptions on one line.

How to output color using argparse in python if any errors happen?

Is there a way to make argparse to output error or warning with colors of red or orange?
I know there are some OS standard colors can be used directly, like "\033[38;5;196m" (red-like) or "\033[38;5;208m" (orange-like), but is there a way to use them or something similar into argparse? Messages with different colors are really helpful for people to recognize if any thing happens.
I just thought of the same question and decided I would poke around the argparse module because the output was kinda weird (On Linux, the words 'error' and 'usage' are usually capitalized, and I also wanted errors to be printed in bold red throughout my program, including when command line arguments were checked.) Here is my code for some nicer looking output, tested using Python 3.6.3 (I really just included more colors as an example here, when in practice you should only need the bold red for errors).
import argparse
import sys
from gettext import gettext
class ColoredArgParser(argparse.ArgumentParser):
# color_dict is a class attribute, here we avoid compatibility
# issues by attempting to override the __init__ method
# RED : Error, GREEN : Okay, YELLOW : Warning, Blue: Help/Info
color_dict = {'RED' : '1;31', 'GREEN' : '1;32',
'YELLOW' : '1;33', 'BLUE' : '1;36'}
def print_usage(self, file = None):
if file is None:
file = sys.stdout
self._print_message(self.format_usage()[0].upper() +
self.format_usage()[1:],
file, self.color_dict['YELLOW'])
def print_help(self, file = None):
if file is None:
file = sys.stdout
self._print_message(self.format_help()[0].upper() +
self.format_help()[1:],
file, self.color_dict['BLUE'])
def _print_message(self, message, file = None, color = None):
if message:
if file is None:
file = sys.stderr
# Print messages in bold, colored text if color is given.
if color is None:
file.write(message)
else:
# \x1b[ is the ANSI Control Sequence Introducer (CSI)
file.write('\x1b[' + color + 'm' + message.strip() + '\x1b[0m\n')
def exit(self, status = 0, message = None):
if message:
self._print_message(message, sys.stderr, self.color_dict['RED'])
sys.exit(status)
def error(self, message):
self.print_usage(sys.stderr)
args = {'prog' : self.prog, 'message': message}
self.exit(2, gettext('%(prog)s: Error: %(message)s\n') % args)

File dialog input with pyqt4 comes up without any font glyphs

I'm trying to create a GUI based application that will perform CRC match between a file copied to card and its source. I'm using PyQT4 from Cygwin with XWindows. When I open up the file dialog to browse to the file that was copied to the card, I donot see file system as one would expect to see when using QFileDialog.getOpenFileName. I see blank squares instead. I've a hunch that this might be due to the fact that it is trying to access a Unix based file system on a Windows machine. Your help is appreciated.
#!/usr/bin/env python
import zlib
import sys
from PyQt4.QtGui import *
def crc(fileName, count):
if count == 0:
return "%X"%(zlib.crc32(open(fileName,"rb").read()) & 0xFFFFFFFF)
else:
return "%X"%(zlib.crc32(open(fileName,"rb").read(count)) & 0xFFFFFFFF)
def compare(cr1, crc2):
if crc1 == crc2:
return "CRC Matched"
else :
return "CRC not Equal"
a = QApplication(sys.argv)
w = QWidget()
w.resize(320, 240)
w.setWindowTitle("CRC Check")
fileName = QFileDialog.getOpenFileName(w, 'Open File', '/')
crc1 = crc(fileName , count = 0)
print "Generated file CRC", crc1
crc2 = crc(fileName = "/dev/sdc", count = 5000000)
print "Copied file CRC", crc2
print compare(crc1, crc2)
w.show()
sys.exit(a.exec_())

Resources