Ceci est une ancienne révision du document !
Table des matières
1
Many years ago, I was dealing with high blood pressure issues. My doctor suggested that I do something that allowed me to concentrate on something fairly useful, but rather trivial. I dealt with it by trying to do counted cross stitch. It’s creative, focused, and keeps your mind occupied on what you are doing, not what is bothering you. I find myself in that position again, so I broke out the hoop and needles and started again. In case you aren’t familiar with counted cross stitch, I’ll give you a gross overview of what it is. Cross stitch is a type of needlework that uses tiny ‘x’ patterns of thread that eventually make up a picture. The thread is called “floss” and the fabric that you use is called “aida”. According to Wikipedia, aida is a special fabric that has tiny squares that have small holes at regular intervals that form the squares. This facilitates the placement of the “x” patterns that make the image. There are two types of cross stitch. One has an image printed on the aida (sort of like paint by numbers), and the other uses totally blank aida that you count stitches from the pattern. The second is much harder than the first. Go to your favorite fabric store or craft section of your local mega-mart and you’ll get the idea.
Il y a plusieurs années, j'avais quelques problèmes de surpression sanguine. Mon médecin m'a suggéré de trouver une activité qui m'obligerait à me concentrer sur quelque chose d'assez utile, mais plutôt simple. Je m'en suis sorti en essayant de faire du point de croix compté. C'est créatif, ciblé, et maintient votre esprit occupé sur ce que vous faites, pas sur ce qui vous dérange. Je me trouve à nouveau dans cette situation, j'ai donc ressorti le cerceau et les aiguilles et j'ai recommencé.
Au cas où vous ne seriez pas familier avec le point de croix compté, je vais vous donner un bref aperçu de ce que c'est. Le point de croix est un type de couture qui consiste à faire des « x » minuscules en fil pour aboutir au final à une image. Le fil est appelé « floss » ou « soie » et le tissu que vous utilisez est appelé « aïda ». Selon Wikipedia, l'aïda est un tissu spécial formé de petits carrés et de petits trous à intervalles réguliers. Ceci facilite le placement des motifs en « x » qui forment l'image. Il existe deux types de point de croix. L'un a une image imprimée sur la toile aïda (une sorte de peinture par numéros), et l'autre utilise une toile aïda totalement vierge et vous comptez les points du motif. La seconde est beaucoup plus compliquée que la première. Allez dans votre magasin de tissu préféré ou à la section loisirs créatifs de votre supermarché local et vous comprendrez.
2
Also a while back, I started playing with creating a program that would take an image and convert it into a cross stitch pattern. One thing lead to another, and I had to shelve the program for other things. I’ve now dusted off the idea and started anew. We will spend the next few articles dealing with this project. It will take a while, since some things are fairly complex and have many parts to them. Here is the “game plan”: • Create a database for the pixel colors to floss colors. • Create a GUI using Tkinter for the application. • Flesh out the application to do the manipulation of the image files. • Create a PDF file that will be the ultimate pattern for the project. What you will learn • Revisitation of database and XML manipulation. • Revisitation of Tkinter GUI programming. If you missed the previous articles on this, please refer to FCM issues 51 thru 54. • Image manipulation using PIL (http://pillow.readthedocs.org/en/latest/). • PDF creation using pyFPDF (https://code.google.com/p/pyfpdf).
J'ai également commencé à m'amuser il y a quelque temps avec la création d'un programme qui prendrait une image pour la convertir en un modèle de point de croix. Une chose en entraînant une autre, j'ai dû laisser le programme de côté pour faire d'autres choses. J'ai maintenant déterré l'idée et commencé à nouveau.
Nous allons traiter ce projet durant les prochains articles. Il faudra un certain temps, car certaines choses sont assez complexes et sont assez spécifiques. Voici le « plan de jeu » : • Créer une base de données pour convertir les couleurs de pixels en couleurs de fils. • Créer une interface graphique avec Tkinter pour l'application. • Étoffer l'application pour faire la manipulation des images. • Créer un fichier PDF qui sera le modèle ultime pour le projet.
Ce que vous apprendrez : • révision sur la manipulation de base de données et XML ; • révision sur la programmation d'interfaces avec Tkinter. Si vous avez raté les précédents articles à ce sujet, merci de vous référer aux numéros 51 à 54 ; • manipulation d'images avec PIL (http://pillow.readthedocs.org/en/latest/) ; • création de PDF à l'aide pyFPDF (https://code.google.com/p/pyfpdf).
3
Getting Started The first thing in our list of tasks is to create the database that will hold the DMC(™) floss colors and reference them to the closest approximation to the RGB (Red, Green, Blue) values that are used in images on the computer. At the same time, the database will hold the hex value and the HSV (Hue, Saturation, Value) representations for each floss color. It seems that HSV is the easiest way to find the “closest” representation of a color that will match the floss colors. Of course, the human eye is the ultimate decision maker. If you are not familiar with HSV color representations, there is a rather complex writeup on Wikipedia at http://en.wikipedia.org/wiki/HSL_and_HSV. It might help, but it might make things less clear. The first thing we need is an XML file that has the DMC floss colors with a RGB conversion. The best one I found is at http://sourceforge.net/p/kxstitch/feature-requests/9/. The file you want is dmc.xml. Download it and put it in a folder that you will use to hold the Python code.
Pour commencer
La première chose dans notre liste de tâches est de créer la base de données qui contiendra les couleurs de fils DMC (™) et de les rapprocher le mieux possible des valeurs RVB (Rouge, Vert, Bleu) utilisées pour les images sur l'ordinateur. La base de données contiendra également la valeur hexadécimale et la représentation HSV (Teinte, Saturation, Lumière) pour chaque couleur de fil. Il semble que le HSV soit la façon la plus simple de trouver la « plus proche » représentation d'une couleur de fil. Bien sûr, l'œil humain est le décideur ultime. Si vous n'êtes pas familier avec les représentations de couleurs HSV, il y a un article assez complexe sur Wikipedia : http://fr.wikipedia.org/wiki/Teinte_saturation_lumi%C3%A8re. Il pourrait aider, mais il pourrait rendre les choses moins claires.
La première chose dont nous avons besoin est un fichier XML qui contient les couleurs de fils DMC avec une conversion RVB. Le meilleur que j'ai trouvé est ici : http://sourceforge.net/p/kxstitch/feature-requests/9/. Le fichier que vous cherchez est dmc.xml. Téléchargez-le et mettez-le dans un dossier que vous allez utiliser pour stocker le code Python.
4
Now we will be using apsw (below) to do our database manipulation, which you should already have and ElementTree to do the XML parsing (which is included in Python version 2.7+). As always, we start with our imports. In this program, we have only the two. We also set the name of the table. The next portion should be familiar if you have been reading the articles for a while. We create a function that will read the XML file, and parse it for us. We then can use the information to load the database. A snippet of the XML file is shown top right. We are looking for the <floss> tag for each line of information. To do this, we use the .findall(‘floss’) command. Once we have the information line, we break each tag (name, description, etc.) into separate variables to place into the database. When it comes to the <color> tag, we use the .floss.findall(‘color’) command to get each value of Red, Green and Blue.
Maintenant, nous allons utiliser apsw (ci-dessous), que vous devriez déjà avoir, pour manipuler la base de données et ElementTree pour faire l'analyse XML (inclus depuis Python version 2.7).
Comme toujours, nous commençons avec nos importations. Dans ce programme, nous n'en avons que deux. Nous réglons également le nom de la table.
La partie suivante devrait vous être familière si vous avez lu les articles depuis un certain temps. Nous créons une fonction pour lire le fichier XML et l'analyser. Nous pouvons ensuite utiliser ces informations pour remplir la base de données. Un extrait du fichier XML est affiché en haut à droite.
Nous recherchons la balise <floss> pour chaque ligne d'information. Pour ce faire, nous utilisons la commande .findall('floss'). Une fois que nous avons la ligne d'information, nous découpons chaque balise (nom, description, etc.) en variables distinctes pour les placer dans la base de données. Quand nous arrivons à la balise <color>, nous utilisons la commande .floss.findall('color') pour obtenir chaque valeur de Rouge, Vert et Bleu.
5
We start by telling the function that we will be using the global variables connection and cursor. We then set the filename of the XML file, parse the XML file, and get started. We also use a counter variable to show that something is happening while the parsing and database inserts are going on. Now that we have all our data, we need to create the SQL insert statement and execute it. Notice the “\” after the word VALUES in the SQL statement. That is a line-continuation character to make it easier for printing here in the magazine. We will be creating the database and table in a few moments. SQL = “INSERT INTO DMC (DMC,Description,Red,Green,Blue) VALUES \ ('%s','%s',%s,%s,%s)” % (name,desc,red,green,blue) cursor.execute(SQL)
6
Now, we print to the terminal window that something is going on: print “Working record {0}”.format(cntr) cntr += 1 Now we create and/or open the database in the OpenDB routine (bottom right). If you’ve been with us when we have done database work before, you will notice that we are using two cursors this time. The cursor variable is used for the “normal” inserts, and later on in the select statement for the update to set the hex and HSV values. We have to use two cursors, since if you modify a cursor in the middle of a logic statement, you lose everything with the new command. By using ‘ucursor’, we can use that for the update statements. Other than that, it is our normal OpenDB routine.
7
Now that the database is created and/or opened, we can set up our table (top right). Notice that the SQL statement below uses the triple quote to allow for the line to break neatly for viewing. The EmptyTables routine (middle right) is there just to make sure that if we want to or need to run the application more than once, we start with a clean and empty table if it exists. IF we were to stop here, we would have a reasonable working database with the DMC color, color name and the RGB values associated with each. However, as I alluded to before, it is easier to pick the closest floss color by using the HSV data. We next create the hex value from the RGB values (middle left).
8
The next function creates the HSV values from the RGB values. I found the algorithm on the internet. You can research it there. Finally, we create the UpdateDB function (next page, top left). We use the SELECT * FROM DMC command and use the “standard” cursor variable to hold the data. We then step through the returned data, and read the RGB values, and pass them to the rgb2hex function as a tuple and to the rgb2hsv function as three separate values. Once we get the return values, we use the update SQL command to match the proper record by using the primary key (pkID). As I stated before, we have to use a separate cursor for the update statement. The last thing we do is call each of the functions in order to create the database, and, at the end, we print “Finished” so the user knows everything is done. OpenDB() MakeTables() EmptyTables() # Just to be safe ReadXML() UpdateDB() print “Finished”
9
I named this program “MakeDB”. The database should be created in the same folder where the code and XML file are located. As always, the full code can be found at http://pastebin.com/Zegqw3pi. Next time, we will work on the GUI. We use Tkinter for the GUI, so, in the meantime, you might want to refresh your memory by looking at FCM issues 51 thru 54 where I take you through Tkinter. Until next time, have a good month.
code en VF : P7gZgNTm
TABLEAUX
page 11
# makedb.py # DMC.xml vers SQLite database # Pour Full Circle Magazine numero 85
import apsw from xml.etree import ElementTree as ET nomtable = “DMC”
page 12-1
inchangé
page 12-2
def LireXML():
global connexion global curseur nomfic = 'dmc.xml' arbre = ET.parse(nomfic) racine = arbre.getroot() compteur = 0 for fil in racine.findall('floss'): nom = fil.find('name').text desc = fil.find('description').text for couleur in fil.findall('color'): rouge = couleur.find('red').text vert = couleur.find('green').text bleu = couleur.find('blue').text
page 12-3
def OuvrirBase():
global connexion global curseur global ucurseur global nombase connexion = apsw.Connection("fils.db3") curseur = connexion.cursor() ucurseur = connexion.cursor()
page 13-1
def CreerTables():
sql = '''CREATE TABLE IF NOT EXISTS DMC (pkID INTEGER PRIMARY KEY, DMC INTEGER, Description TEXT, Rouge INTEGER, Vert INTEGER, Bleu INTEGER, HEX TEXT,H INTEGER,S INTEGER,V INTEGER)''' curseur.execute(sql)
page 13-2
def rgb2hex(rgb):
return '%02x%02x%02x' % rgb
def ViderTables():
sql="DELETE FROM %s" % nomtable curseur.execute(sql)
page 13-3
inchangé