Convertir Tarjeta Perforada en archivo digital. From Punch Card to digital file. (Script MacOS).

Convertir Tarjeta Perforada en archivo digital (.PNG).
From Punch Card to digital file (.PNG)
(Script para / for MacOS).

Hay una multitud de tarjetas perforadas con diseños para nuestras tricotosas en Internet, además de las que podemos encontrar en libros y revistas especializadas, e incluso, tarjetas físicas que tengamos con nosotr@s.

There is a lot of punch cards with designs for our knitting machines on the Internet, in addition to those found in books and specialized magazines, and even physical cards that we have with us.

A la hora de utilizar AYAB o img2track, tendremos que crear un archivo de 1bit con extensión .PNG, (es decir puntos blancos y negros) y si el dibujo o tarjeta es amplio, será una labor algo tediosa que realizar, fácil sí, pero os llevará tiempo. No podemos usar imágenes en JPG ya que no son entendidas por ninguno de los dos programas.

When using AYAB or img2track, we will have to create a 1bit file with .PNG extension, (ie black and white dots) and if the drawing or card is large, it will be a tedious task to do, easy yes, but it will take time. We can not use images in JPG since they are not understood by either of the two programs.

Con la ayuda de la Comunidad: https://www.macuarium.com/foro/
y el trabajo del usuario registrado APB, hemos podido conseguir un Script (programa muy simple), que hace que dicho proceso sea muy fácil. Desgracidamente, por el momento, está disponible para usuarios de ordenadores Mac, pero espero que un futuro cercano se pueda hacer lo mismo en Windows, incluso Linux. ***Si alguien sabe y nos quiere ayudar, que se ponga en contacto conmigo***.

With the help of the Community: https://www.macuarium.com/foro/
and the work of the registered user APB, we have been able to get a Script (very simple program), which makes this process very easy. Unfortunately, at the moment, it is available for Mac computer users, but I hope that in the near future it will be possible to do the same in Windows, even Linux. *** If someone knows and wants to help us, please contact me ***.

Para que entendáis bien el proceso, os he preparado un videotutorial sobre la creación del Script en MacOS y del funcionamiento del mismo (es más fácil de lo que creéis):

For you to understand the process well, I have prepared a video tutorial about the creation of the Script in MacOS and how it works (it’s easier than you think):

A continuación está el código de programación del Script (para que podáis seguir el videotutorial y crearos vuestra aplicación):

Next is the Script programming code (so you can follow the video tutorial and create your application):

-- Creat amb ApplescriptObjC
-- ** Gracias a / Thanks to APB User Barcelona del / from Foro Macuarium Forum **
-- ** Más información / More info at knitstudium.com **


-- TEXTO PARA TRADUCIR --
set peticioArxiu to "Archivo Inicial / Initial File"
--set nomArxiuResultat to "Final.jpg"
set nomArxiuResultat to "Final.png"
set peticioReticula to "Tamaño de la retícula / Screen size:"
set respostaPerDefecte to "Horizontal, vertical"
set botoCancel to "Cancelar/Cancel"
set botoQuadrada to "Cuadrada/Square"
set botoRectangular to "Rectangular"
set errorValorsRet to "Han de ser dos números separados por una coma. / They must be two numbers separated by a comma."



-- ** NO TRADUCIR **
use scripting additions
use framework "Foundation"
use framework "AppKit"

-- classes, constants, and enums used
property NSString : a reference to current application's NSString
property NSImage : a reference to current application's NSImage
property NSBitmapImageRep : a reference to current application's NSBitmapImageRep
property NSGraphicsContext : a reference to current application's NSGraphicsContext
property NSCalibratedRGBColorSpace : a reference to current application's NSCalibratedRGBColorSpace
property NSCalibratedWhiteColorSpace : a reference to current application's NSCalibratedWhiteColorSpace
property NSTIFFCompressionLZW : a reference to current application's NSTIFFCompressionLZW --a reference to 5

property NSBitmapImageFileTypeJPEG : a reference to current application's NSBitmapImageFileTypeJPEG
property NSBitmapImageFileTypeTIFF : a reference to current application's NSBitmapImageFileTypeTIFF
property NSBitmapImageFileTypePNG : a reference to current application's NSBitmapImageFileTypePNG
property NSBitmapImageFileTypeBMP : a reference to current application's NSBitmapImageFileTypeBMP
property NSBitmapFormatAlphaFirst : a reference to current application's NSBitmapFormatAlphaFirst
property NSBitmapFormatAlphaNonpremultiplied : a reference to current application's NSBitmapFormatAlphaNonpremultiplied
property NSCompositingOperationSourceOver : a reference to current application's NSCompositingOperationSourceOver
property NSCompositingOperationCopy : a reference to current application's NSCompositingOperationCopy
property NSColorRenderingIntentSaturation : a reference to current application's NSColorRenderingIntentSaturation
property NSColorRenderingIntentDefault : a reference to current application's NSColorRenderingIntentDefault
property genericGrayColorSpace : a reference to current application's genericGrayColorSpace
property NSColorSpace : a reference to current application's NSColorSpace



-- Escullir arxiu imatge
set arxiuImatge to POSIX path of (choose file of type "public.image" with prompt peticioArxiu)

set carpetaResultat to POSIX path of (path to desktop folder) --(path to desktop folder as string)
set arxiuResultat to NSString's stringWithString:(carpetaResultat & nomArxiuResultat)

--Esborrar arxiu resultat anterior
try
	tell application "Finder" to delete (POSIX file (carpetaResultat & nomArxiuResultat)) as alias
end try

--Demanar mida retícula de l'imatge 
set abc to ""
repeat while abc is ""
	set aaa to display dialog peticioReticula default answer respostaPerDefecte buttons {botoCancel, botoQuadrada, botoRectangular} default button 3
	if button returned of aaa is botoCancel then error number -128
	set reticulaQuadrada to button returned of aaa is equal to botoQuadrada
	set aaa to text returned of aaa
	set AppleScript's text item delimiters to the ","
	try
		set columnesFinal to (first text item of aaa) as number
		set filesFinal to (second text item of aaa) as number
		set abc to "OK"
	on error
		display alert errorValorsRet as critical
	end try
	set AppleScript's text item delimiters to the ""
end repeat

-- load images and get the size
set imatgeOriginal to NSBitmapImageRep's imageRepWithContentsOfFile:(NSString's stringWithString:arxiuImatge)

set {width:columnesOrig, height:filesOrig} to imatgeOriginal's |size|()
--set ddd to imatgeOriginal's scale()

--calcular proporció
set espaiPixelColumna to columnesOrig / columnesFinal
if reticulaQuadrada then
	set espaiPixelFila to espaiPixelColumna
else
	set espaiPixelFila to filesOrig / filesFinal
end if

-- make new bitmapImage
-- Imatge a tot color
set imatgeNova to (NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:columnesFinal pixelsHigh:filesFinal bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(NSCalibratedRGBColorSpace) bitmapFormat:NSBitmapFormatAlphaFirst bytesPerRow:0 bitsPerPixel:32)

--- store the existing graphics context
NSGraphicsContext's saveGraphicsState()

-- set graphics context to new context based on the new bitmapImageRep
(NSGraphicsContext's setCurrentContext:(NSGraphicsContext's graphicsContextWithBitmapImageRep:imatgeNova))

-- manipulant els pixels

repeat with filaPixel from 0 to (filesFinal - 1)
	set filaPixelOrig to round (espaiPixelFila * filaPixel + espaiPixelFila / 2)
	repeat with columnaPixel from 0 to (columnesFinal - 1)
		set columnaPixelOrig to round (espaiPixelColumna * columnaPixel + espaiPixelColumna / 2)
		
		(imatgeOriginal's drawInRect:{origin:{x:columnaPixel, y:filaPixel}, |size|:{width:1, height:1}} fromRect:{origin:{x:columnaPixelOrig, y:filaPixelOrig}, |size|:{width:1, height:1}} operation:NSCompositingOperationCopy fraction:1.0 respectFlipped:true hints:(missing value))
		
	end repeat
end repeat

-- converteix el resultat a grisos
set imatgeNova to (imatgeNova's bitmapImageRepByConvertingToColorSpace:(NSColorSpace's genericGrayColorSpace) renderingIntent:NSColorRenderingIntentDefault)

-- restore graphics state
NSGraphicsContext's restoreGraphicsState()


-- save bitmapImageRep as image
set theData to (imatgeNova's representationUsingType:NSBitmapImageFileTypePNG |properties|:{NSImageInterlaced:true})

theData's writeToFile:arxiuResultat atomically:true
Con la ayuda de un Script (programa sencillo) se consigue que una imagen sea transformada en unos segundos en un archivo .PNG para poder ser usada directamente en AYAB y/o img2track. ***** With the help of a Script (simple program), an image can be transformed in a few seconds into a .PNG file to be used directly in AYAB and / or img2track.
Con la ayuda de un Script (programa sencillo) se consigue que una imagen sea transformada en unos segundos en un archivo .PNG para poder ser usada directamente en AYAB y/o img2track. ***** With the help of a Script (simple program), an image can be transformed in a few seconds into a .PNG file to be used directly in AYAB and / or img2track.

P.D.: La ópcion “Cuadrada/Square” se usa cuando la imagen está recortada por un lado, dicho lado tiene que ser el superior. Si recortáis bien la imagen, no debéis usar dicho botón.

P.S.: The “Cuadrada / Square” option is used when the image is cropped on one side, that side has to be the upper one. If you trim the image well, you should not use the button.

English explanation (video YouTube):
Take a knitting chart from a punchcard or chart in a magazine, clean it up first in any image-manipulation program such as Gimp to minimize the gridlines and get it as strongly black/white as possible. Then run it through the script, which reduces it to the number of pixels you specify. Then do a final touch-up by hand.

Take a knitting chart from a punchcard or chart in a magazine, clean it up first in any image-manipulation program such as Gimp to minimize the gridlines and get it as strongly black/white as possible. Then run it through the script, which reduces it to the number of pixels you specify. Then do a final touch-up by hand.

The video starts with how to set up and use the script. Then the second half is some suggestions about how to prepare and clean up the image before sending it through the script.
The script is written in AppleScript, to use it your Mac has the Script Editor program, find it in Applications/Utilities. Paste in Victor’s code, click the Compile button, then export it as an application. When you run the app, it asks you which image, and what pixel size you want. Then it creates a file called Final.png on your desktop. Open that again in an image editor, you’ll find that it’s now a tiny file in mostly black and white, you may need to do some final touchup editing. It will have some shades of gray which you can edit out if you wish by painting that pixel over in white or black. AYAB can handle some gray pixels, it will treat a gray below 50% as white and above as black, but it’s cleaner to have as little gray as possible. 
(By the way, AYAB can knit from a jpg file, but I agree that png is generally preferable. Files must not have layers.)
For my experiment, I took this screenshot from an online scanned copy of Stitchworld1, pattern 419.

Espero que os guste y sea de ayuda!!!
Saludos.
Víctor M. Gómez.

Anuncios

2 Comments

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s