Пикс 2 рисовать играть. Приложение pix2pix для компьютера. pix2pix — что это за программа


Алгоритм pix2pix научился распознавать в эскизах людей и превращать их в «реалистичное» изображение. Выходит, скорее, не очень реалистично - зато очень жутко. Это не первый алгоритм проекта: несколько месяцев назад в интернете уже рисовали уродливых котов c pix2pix. Не смогли устоять и на этот раз.

«Новый pix2pix для лиц (рисунки не мои, я импортировал их, используя стороннюю программу)».

Правда, если скетч исполнен не гениально, то алгоритм выдаёт изображения, которые сложно назвать реалистичными - скорее, кошмарными. И в этом убедились пользователи твиттера, которые не устояли перед новой забавой. Получилось как-то не очень.

«Я решила использовать этот pix2pix и нарисовала несколько мультяшных персонажей в нём. Результаты более ужасающие, чем я ожидала увидеть».

«Глубоко расстраивает».

«Я собирался сделать «жуткого рыбного монстра», но нейросеть pix2pix сделала мне кое-что получше, добавив ему причёску, как у участника бойз-бенда».

«Слегка жутко…»

«Это кошмарно!»

Впрочем, даже печальные результаты не могут отбить у пользователей твиттера тяги к творчеству.

«Больше веселья!»

«Нравится этот инструмент!»

«Парень № 3 выглядит хорошо».

«Впечатляющий генератор лиц из эскизов».

Проект pix2pix стал известным несколько месяцев назад благодаря своему алгоритму, который на основе нейросетей переводил нарисованных от руки котиков в «реалистичных». Ну, реалистично выглядел только котик, которого нарисовали сами создатели. А вот то, что творили в приложении обычные пользователи, гораздо больше походило на меховых монстров, чем на котов в привычном понимании этого слова.

«Зацените-ка моего кота. Любой может быть художником».

Размах нейросетей впечатляет, и поэтому их используют и для более серьёзных вещей, чем рисование страшилок. Например, недавно порносайты запустили сервис, который . Правда, судя по результату, этому алгоритму ещё учиться и учиться. Иначе зачем ему сравнивать Елену Мизулину с Бруклин Чейз?

Разработчик Заид аль-Яфии (Zaid Alyafeai) из Университета нефти и ископаемых имени короля Фахда создал браузерную версию системы pix2pix — она в реальном времени превращает наброски пользователя в фотографии. Пока сервис умеет перерисовывать только кошек, фасады зданий и обувь. Исходный код проекта опубликован на GitHub.

Алгоритм

При рисовании фасадов домов алгоритм разбивает изображение на области с объектами разных типов. Например, крыша или окно будут иметь разные цвета. В этом режиме можно рисовать не линии, а прямоугольники:

Специалисты из Калифорнийского университета в Беркли представили алгоритм pix2pix на генеративно-состязательной нейросети в 2016 году. Изначально авторы создали систему, которую требовалось развернуть на компьютере. Сторонние специалисты смогли перенести ее в браузер, но алгоритм принимал в качестве входных данных только завершенный набросок и работала на сервере, поэтому сервис закрыли.

В августе 2018 года Microsoft систему искусственного интеллекта XiaoIce считывать картинку и генерировать китайские стихи с описанием того, что на ней изображено. По словам ученых, современная китайская поэзия требует большого воображения и творческого использования языка, что является сложной задачей даже для человека.

За последние годы искусственные нейронные сети произвели огромный прорыв в мире IT. На мобильных платформах высокую популярность приобрели приложения и фоторедакторы на основе нейросети. Сегодня мы познакомимся с новым развлекательным сервисом – Pix2Pix, выстроенным на технологии компьютерной нейросети. Мы расскажем где и как можно скачать и запустить этот сервис, что бы рисовать онлайн.

Что это такое?

Сервис Pix2Pix – это игровая программка, которая на основе набросков создает реалистичные изображения. Так, вы можете нарисовать от руки портрет, а программа в момент выдаст вам отредактированное фото. Вы сможете рисовать кошек, фасады зданий, обувь, сумки.

В основе успеха пикступикс лежит колоссальная работа: участники проекта обработали более 100 тыс. фото, для обучения нейронной сети. Конечно, данной технологии еще далеко до идеала – частенько, созданные образы представляют из себя ни что иное, как персонажей ужасов. Но с такими темпами развития Pix2pix пойдет далеко и возможно скоро будет применяться в полиции, при составлении фотороботов.

Где и как запустить онлайн?

Итак, если вы хотите оживить свои творения, тогда милости прошу вот на эту страничку – affinelayer.com . Здесь вы сможете порисовать кошек, здания, сумки и обувь. В использовании тут все просто: жмем “Clear”, после рисуем образ и кликаем “Process”. Не взрослым, так детям пойдет играть.

К сожалению, азарта и запала с этим сайтом надолго не хватит – всем хочется создавать портреты людей, а этой опции на нем нет. Мне самому хотелось нарисовать именно человека, поэтому пришлось порыться в буржунете, где меня ждало разочарование. Как я понял, на официальном сайте фотогенератора говорится: сервис закрыт ввиду того, что большой поток пользователей перегружает серверы сайта . Довольно странно, как по мне! Временно это или нет – неизвестно. Возможно сейчас ПиксТуПикс будут дорабатывать, что бы предоставить уже конечный продукт, где будут платные опции.

Играть Pix2Pix на ПК через эмулятор

Решил я не сдаваться и запустить фотогенератор через эмулятор Андроид приложений – Nox App Player 5 . По моему, пока это один из лучших эмуляторов для Windows. Вот как это сделать:

  1. Проходим на официальный веб-сайт эмулятора, где загружаем его инсталл. Кстати, недавно вышла версия 5, где исправлено много багов и недочетов.
  2. По установке нет ничего нового – все стандартно, следуя за Мастером. Только одно замечу – внимательно смотрим в лицензионку, там нужно будет снять галочки.
  3. После запуска Нокса, вам предложат активировать ваш Google аккаунт, что позволит вам качать с Маркета.
  4. Дальше все по стандарту – заходим в Плей Маркет и качаем.

К сожалению, тут меня также ждало разочарование. Представленные в Маркете клоны программы лишь приближенно напоминают Pix2Pix. Даже оценки от пользователей об этом свидетельствуют. Например, одноименная программка меня сразу перекинула на отключенный сервис. Вообщем тут пробуйте, ищите.

Neural City

Another experiment from Mario was training the generator on YouTube videos of Francoise Hardy , then tracking the face of KellyAnne Conway while she explained “alternative facts,” and generating images of Francoise Hardy from those found landmarks, effectivly making Francoise Hardy pantomime the facial gestures of KellyAnne Conway.

Riffing on this technique, I made a webcam-enabled pix2pix trained on pictures of Donald Trump’s face giving a speech. The real-time application was run live for a workshop.

Person-to-person pix2pix

Using pix2pix

The following is a tutorial for how to use the tensorflow version of pix2pix. If you wish to, you can also use the original torch-based version or a newer pytorch version which also contains a CycleGAN implementation in it as well. Although these instructions are for the tensorflow version, they should be fairly relevant to the others with just minor modifications in syntax. You should be able to use any of the versions and get similar results.

In using pix2pix, there are two modes. The first is training a model from a dataset of known samples, and the second is testing the model by generating new transformations from previously unseen samples.

Training pix2pix means creating, learning the parameters for, and saving the neural network which will convert an image of type X into an image of type Y. In most of the examples that we talked about, we assumed Y to be some “real” image of dense content and X to be a symbolic representation of it. An example of this would be converting images of lines into satellite photographs. This is useful because it allows us to generate sophisticated and detailed imagery from quick and minimal representations. The reverse is possible as well; to train a network to convert the real imagery into its corresponding symbolic form. This can be useful for many practical tasks; for example automatically finding and labeling roads and infrastructure in satellite images.

Once a model has been generated, we use testing mode to output new samples. For example, if we trained X->Y where X is a symbolic form and Y is the real form, then we make generative Y images from previously unseen X symbolic images.

Installation

In order to run the software on your machine, you need to have an NVIDIA GPU which is supported by CUDA. Here is a list of supported devices . At least 2GB of VRAM are recommended, although realistically, with less than say 4GB, you may have to produce smaller-sized samples. If you have an older laptop, consider using a cloud-based platform instead (todo: make a guide about cloud platforms).

Install CUDA

Once you have successfully run the installer for CUDA, you can find it on your system in the following locations:

  • Mac/Linux: /usr/local/cuda/
  • Windows: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0

In order for your system to find CUDA, it has to be located in your PATH variables, and in LD_LIBRARY_PATH for Mac/Linux. The installer should do this automatically.

Install cuDNN

cuDNN is an add-on for CUDA which specifically implements operations for deep neural nets. It is not required to run Tensorflow but is highly recommended, as it makes many of the programs much more resource-efficient, and is probably required for pix2pix.

You have to register first with NVIDIA (easy) to get access to the download. You should download the latest version for your platform unless you have an older version of CUDA. At time of this writing, cuDNN 5.1 works with CUDA 8.0+, although cuDNN 6.0+ should work as well.

Once you’ve download cuDNN, you will see it contains several files in folders called “include”, “lib” or “lib64”, and “bin” (if on windows). Copy these files into those same folders inside of where you have CUDA installed (see step 1)

Install tensorflow

Follow tensorflow’s instructions for installation for your system. In most cases this can be done with pip.

Install pix2pix-tensorflow

Clone or download the above library. It is possible to do all of this with the original torch-based pix2pix (in which case you have to install torch instead of tensorflow for step 3. These instructions will assume the tensorflow version.

Training pix2pix

First we need to prepare our dataset. This means creating a folder of images, each of which contain an X/Y pair. The X and Y image each occupy half of the full image in the set. Thus they are the same size. It does not matter which order they are placed into, as you will define the direction in the training command (just remember which way because you need to be consistent).

Additionally, by default the images are assumed to be square (if they are not, they will be squashed into square input and output pairs). It is possible to use rectangular images by setting the aspect_ratio argument (see the optional arguments below for more info).

Then we need to open up a terminal or command prompt (possibly in administrator mode or using sudo if on linux/mac), navigate (cd) to the directory which contains pix2pix-tensorflow, and run the following command:

python pix2pix.py --mode train --input_dir /Users/Gene/myImages/ --output_dir /Users/Gene/myModel --which_direction AtoB --max_epochs 200

replacing the arguments for your own task. An explanation of the arguments:

--mode : this must be “train” for training mode. In testing mode, we will use “test” instead.

--input_dir : directory from which to get the training images

--output_dir : directory to save the model (aka checkpoint)

--which_direction : AtoB means train the model such that the left half of your training images is the input and the right half is the output (generated). BtoA is the reverse.

--max_epochs : number of epochs (iterations) to train, i.e. how many times to each image in your training set is passed through the network in training. In practice, more is usually better, but pix2pix may stop learning after a small number of epochs, in which case it takes longer than you need. It is also sometimes possible to train it too much, as if to overcook it, and get distorted generations. The loss function does not necessarily correspond well to quality of images generated (although there is recent research which does create a better equivalency between them).

Note also that the order in which parameters are written in the command does not actually matter. Additionally, there are optional parameters which may be useful:

--checkpoint : a previous checkpoint to start from; it must be specified as the path which contains that model (so it is equivalent to –output_dir). Initially you won’t have one but if your training is ever interrupted prematurely, or you wish to train for longer, you can initialize from a previous checkpoint instead of starting from scratch. This can be useful for running for a while and checking to see quality, and then resuming training for longer if you are unsatisfied.

--aspect_ratio : this is 1 by default (square), but can be used if your images have a different aspect ratio. If for example your images are 450x300 (width is 450), then you can use an aspect_ratio 1.5.

--output_filetype : png or jpg

There are more advanced options, which you can see in the arguments list in pix2pix.py. The adventurous may wish to experiment with these as well.

Unfortunately, pix2pix-tensorflow does not currently allow you to change the actual size of the produced samples and is hardcoded to have a height of 256px. Simply changing it in pix2pix.py will result in a shape mismatch. If you wish to generate bigger samples, you can do so using the original torch-based pix2pix which does have it as a command line parameter, or more adventurously adapt the tensorflow code to arbitrarily sized samples. This will require changing the architecture of the network slightly, perhaps as a function of a –sample_height parameter, which is a good exercise left to the intrepid artist.

In practice, trying to generate larger samples, say 512px does not always lead to improved results, and may instead look not much better than an upsampled version of the 256px versions, at the cost of requiring significantly more system resources/memory and taking longer to finish training. This will definitely be true if your original images are smaller than the desired size because subpixel details are not available in the training data, but even if your data is sized sufficiently, it may still occur. Worth trying out, but your results may vary.

Once you run the command, it will begin training, updating the progress periodically and will consume most or all of your system’s resources so it’s often worth running overnight.

Testing or generating images

The second operation of pix2pix is generating new samples (called “test” mode). If you trained AtoB for example, it means providing new images of A and getting out hallucinated versions of it in B style.

In pix2pix, testing mode is still setup to take image pairs like in training mode, where there is an X and a Y. This is because a useful thing to do is to hold out a test or validation set of images from training, then generate from those so you can compare the constructed Y to the known Y, as a way to visually evaluate the data. pix2pix helpfully creates an HTML page with a row for each sample containing the input, the output (constructed Y) and the target (known/original Y). Several of the downloadable datasets (e.g. facades) are packaged this way. In our case, since we may not have the corresponding Y (after all, that’s the whole point!) a quick workaround for this problem is to simply take each X, and convert into an image twice the width where one half is the image to use as the input (X) and the other is some blank decoy image. Make sure you are consistent with how it was trained; if you trained –which_direction AtoB, the blank image is on the right, and BtoA it is on the left. If the generated html page shows the decoy as the “input” and the output is the nondescript “Rothko-like” image, then you accidentally put them in the wrong order.

Once your testing data has been prepared, run the following command (again from the root folder of pix2pix-tensorflow):

python pix2pix.py --mode test --input_dir /Users/Gene/myImages/ --output_dir /Users/Gene/myGeneratedImages --checkpoint /Users/Gene/myModel

An explanation of the arguments:

--mode : this must be “test” for testing mode.

--input_dir : directory from which to get the images to generate

--output_dir : directory to save the generated images and index page

--checkpoint : directory which contains the trained model to use. In most cases, this should simply be the same as the –output_dir argument in the original training command.

todo: example images through training and testing process

todo: make a CycleGAN guide

– удивительное приложение, которое умеет превращать обычные рисунки в реалистичные картины великих мастеров искусства. Этот небольшой инструмент для Android способен научить вас красиво рисовать даже если вы никогда не приписывали себя в ряды художников и даже не знаете, как правильно держать кисть. Теперь достаточно изобразить на экране любую каляку-маляку, подождать несколько секунд и удивляться получившемуся шедевру.

Пускай система Pix2Pix пока ещё несовершенна, ведь это только вторая версия приложения, однако уже сейчас программа сможет немало удивить вас. В основе разработки лежит уже немного знакомая нам технология редактирования изображений при помощи нейронных сетей. Вы наверняка уже могли видеть на какие чудеса способны Призма или . Но сейчас перед нами совсем необыкновенный продукт, не похожий ни на один другой. Только представьте – вы рисуете какого-нибудь котика или даже своего соседа по парте, причём не особо стараясь, а Пикс2пикс превращает ваши каляки-маляки в потрясающие шедевры. Возможно, появись эта мобильная программа намного раньше, она понравилась бы самому Пикассо! Но повезло только нам, ведь только мы, современные люди, получили уникальный шанс использовать мобильные технологии на полную катушку. Прокачайте свой смартфон или планшет прямо сейчас, добавьте удивительную возможность превращать рисунок в картину, и вы обязательно поразите своими новыми способностями всех друзей!

Как пользоваться Pix2Pix на Андроид:

Откройте приложение, следуйте несложным инструкциям
После нескольких нажатий кнопки «далее» вы попадёте на основной экран мобильной программы
Не пренебрегайте полезными советами и подсказками разработчика
Нарисуйте свой рисунок и подождите несколько мгновений, пока система сгенерирует изображение
Программа работает в режиме online, поэтому не забудьте заранее включить Интернет

Не расстраивайтесь, если у вас не получилась с первого раза идеальная картина. Приложение изначально рассчитано на то, чтобы просто поднять вам настроение. Возможно, разработчик ещё не довёл своё творение до совершенства и ему есть над чем поработать, зато вам с друзьями никогда не будет скучно. Поэтому не оценивайте программу слишком серьёзно, мы предлагаем скачать Pix2Pix развлечения ради. Приноровившись, можно создать поистине волшебный шедевр, но иногда ведь хочется просто повеселиться. Не отказывайте себе в удовольствии и вы, играйте, шутите и получайте от этого необычного приложения только положительные эмоции!