Bad Apple или с Днем Радио, гики
Сегодня очень немного было поздравлений с профессиональным праздником некоторых гиков, хотелось бы поднять настроение себе и остальным, достать что-то такое любимое теплое ламповое… И да! это будет приятный человеческому глазу зелёный осциллограф.
Как все знают, прибор осциллограф очень простой, обычно используется для наблюдения сигналов в реальном (теперь уже и не только) времени, осциллографы развиваются, становятся цифровыми, но так было не всегда. К сожалению, первое поколение осциллографов с приятным аналоговым зелёным цветом вымирает, а ещё столько всего можно с ними сделать. Так почему бы не сегодня.
Кроме того, чтобы показывать сигналы, на нем хотелось бы получить что-то более осязаемое и почему бы это не Bad Apple, и почему бы не «простым» каким-то способом.
Идея пришла в голову предельно простая (каемся, что она даже уже где-то описана), использовать VGA видеовыход, а именно цветные сигналы R, G, B для кодирования положения луча. Один, например, R использовать для отклонения луча по X, второй G для Y, а B — для отключения луча, во время обратного хода строки и кадра.
Но Bad Apple сам по себе растровый-растровый, а нужно его перевести в вектор. Так как мы не в раз не программисты, посыпая голову пеплом, решили забивать гвозди микроскопом, а именно взяли матлаб и с помощью функции bwtraceboundary выделили контура растровых объектов, декодировали, отфильтровали, а получившиеся вектора обошли. Что-то подфильтровали.
И, на наше удивление получили довольно четкий контур. Для радиотехников, которые скорее на «вы» по обработке изображений, без глубоких копаний в математику — был очень даже прогресс.
Далее полученные вектора перегнали в обход луча, а уже луч растянули на вот такое растровое изображение кадра. Это та же картинка, что и выше, но уже цветом закодировано положение точки на изображении.
Дальше 16 мегабайтный исходный Bad Apple был перегнан в 13ГБайтный Green Apple c вот таким результатом =)))
С Днем Радио, коллеги! не знаем как вы, но по крайней мере этот день мы провели в окружении теплой ламповой техники.
P.S.: Некоторые могут правильно заметить, что C1-94 не имеет возможности смещения луча по Х, изображение должно было быть смещено на пол-экрана вправо, но это не монтаж, для смещения добавлен внешний операционный усилитель.
Ну и в качестве некоторой полезности, зачем это может понадобиться.
Самый приятный бонус — это возможность сделать для себя зелёные часы, которые в заголовке статьи, ещё бы оснастить будильником и был бы вообще класс, я бы поставил у себя дома, несмотря на габариты.
Ещё один приятный бонус, когда есть возможность сформировать точную развертку на экране осциллографа — это довольно детальный замер времени экспозиции видео или фотокамеры.
Для примера, если сформировать вот такую развертку:
где каждый штрих — это 10мкс, можно с точностью около 5мкс определять длительность экспозиций, при этом длительностью единицы миллисекунд, если создать несколько таких таблиц, то можно измерять экспозиции камеры в разных интервалах от единиц микросекунд до примерно до 1/25 секунды (и даже больше).
Выглядит замер на видеокамере примерно так:
здесь экспозиция составила 520мкс. К сожалению, немного мешает послесвечение люминофора, но это вопрос практики и выбора осциллографа с минимальным послесвечением.
Так что вот так =) надеюсь, было интересно и хотя бы немного скрасило будни серого карантина.
Ваши Pyhesty, которому пришла идея и Алексей, который реализовал прекрасное Зеленое Яблоко на C1-94.
Источник
Bad Apple!! Meme
Popular:
Bad Apple!!
About
«Bad Apple!!» is a Japanese dance pop song originally featured in one of the arcade games from the Touhou series. Since its rise to popularity on Nico Nico Douga (NND) in 2009, the song has inspired an extensive list of remixes, dances and musical tributes primarily on the Japanese web. In October 2010, the original upload became the first NND video to reach 10 million views.
Background
The Touhou series is a Japanese indie scrolling manic shooter game created by Team Shanghai Alice’s sole member, ZUN. Touhou games have a strong following in Japan and it is far from uncommon to see most Touhou soundtracks being remixed by various doujin circles [1] , some of them giving birth to other phenomena such as U.N Owen Was Her? and Night of Knights.
Origin
The Song
«Bad Apple!!» was originally included in the soundtrack of Level Stage 3 in the 4th Touhou Project game Lotus Land Story [2] , created by series designer ZUN [3] and released in July 1998.
On May 20th, 2007, Masayoshi Minoshima, the founder of well-known, Touhou-affiliated doujin club Alstroemeria Records [4] released a remix of «Bad Apple!!» featuring the voice of Japanese pop singer Nomico [5] in an album called Lovelight [6] .
Early MAD Videos
One of the first MADs of «Bad Apple!!» was uploaded on March 28th, 2008. While its peak has likely passed, MADs based on the song are still being published on YouTube [7] to this day.
Viral instance: Stylized Shadow Art
On June 8th 2008, a Nico Nico user made a video [8] featuring a storyboard with precise details of what he considered would be the best video clip for the «Bad Apple!!» song. His video has accumulated more than 900,000 views on Nico Nico Douga alone. Here is a translated version available on YouTube:
As the idea began to spark interest, the first draft [9] video was uploaded on October 26th, 2008:
«Bad Apple!!» exploded on October 27, 2009 when Nico Nico Douga user Anira (あにら) released the last draft of his work on the video [10] , inspired by the 2008 fan version. This video, made with 3D moving models and silhouette shadow art featuring a great amount of the female cast from the Touhou series hit YouTube the same day. In addition, the original NND video became the first to reach 10 million views , making it one of the most watched videos in the Japanese video-sharing community (English subtitled version [11] ).
As a result of the video’s success, many Touhou articles [12] were published, mostly praising it as an art form.
Derivatives: Stylized Shadow Videos
While that video clip was far from being the first one in history to employ shadow and light in an artistic manner, this silhouette art instance launched its own trend of parodies. This was first translated by videos featuring other Japanese CGI models, mostly Miku Miku Dance [14] related clips:
There were also video comparisons/compilations between the original clip and previous fan-made animations:
But overall, many users tried to recreate the initial clip using alternative artistic tools, like Laser Show (October 2009) :
Sand Art Effect (November 2009) :
Apple Peeling (February 2010) :
CNN News: Bad Apple in Stop-Motion
One of the most popular MADs of «Bad Apple!!» uses stop-motion animation where the director printed out every individual frame of the shadow video and uses contextual frame placement, published January 2010:
While most of the parodies, remixes, and MADs were made by people knowing at least a little bit about what Touhou is, the rest of the world was bound to discover the stop-motion animation clip when CNN made a report about it on January 30th 2010 :
However, in it, the reporters mistakenly credited the stop-motion alteration as being the initial video describing how the Stylized Shadow one has been made, which unleashed many fans to leave raging comments [15] about it.
Dance Videos
Before the 3D shadow MAD, «Bad Apple!!» was already popular on Nico Nico Douga as a dance fad from people inventing a dance fitting the song. In a manner similar to the Fukkireta meme, the Odotte Mita (踊ってみた) or “I tried dancing it” fad on NND took hold.
It first began on June 27th 2009 when two Japanese boys uploaded themselves dancing to the song on Nico Nico Douga [16] (Registration Required).
The duet performance gave birth to more than 100 videos [17] of people following the dance, featuring either human beings or 3D characters.
Performances / Tributes
While others, pertaining to a Japanese fad called Hiite Mita (弾いてみた) or «I tried playing it» can be considered as covers and can feature nearly every kind of instrument :
Violin
Piano
Guitar
Fan Dubs
Another peculiar fad on Nico Nico Douga involving a song meme, Utatte Mita (歌ってみた) or «I’ve tried singing it» involves people singing the tune, recording and posting it to Nico Nico Douga or other video streaming sites. This fad isn’t restricted to the Japanese web and fandubs exist as well :
External Refernces
[8] NicoNicoDouga — 【UP主が見たい】Bad Apple!! PV【誰か描いてくれ】 (Registration Required) / Posted on 6-08-2008
[9] YouTube — [東方手描き]BAD APPLE!! / Posted on 10-26-2008
[10] NicoNicoDouga — 【東方】Bad Apple!! PV【影絵】 (Registration Required) / Posted on 10-27-2009
[11] YouTube — Bad Apple!! / Posted on 10-29-2009
[12] Polymetrica — Bad Apple!! Shadow Art PV / Posted on 10-27-2009
Источник
Boxing in bad apple
Bad Apple printed out on the console with Python!
A word of disclaimer, while the final code is somewhat original, this project is an amalgamation of different code snippets that I found online. As the main YouTube Video begins to gain traction, I feel the need to inform the audience that this code is NOT ENTIRELY ORIGINAL.
The concept of playing Bad Apple!! on a Command Line Interface (CLI) is not a novel idea and I am definitely not the first.
There are many iterations and versions around YouTube and I wanted to give it a shot. The intent of posting the video on YouTube was to show a few friends of a simple weekend project that I whipped up in Python.
My own video can be found here.
Running this code/Pre-requisites
Thanks to TheHusyin for adding a requirements.txt file for easier installs.
You can either git clone or download a ZIP of this repository.
git clone https://github.com/CalvinLoke/bad-apple
Then, ensure that you set your terminal to the directory of this repository.
Install the necessary dependencies and packages by using:
pip install -r requirements.txt
And to run the code:
And just follow the on-screen prompts.
Currently, my implementation of a rudimentary static time.sleep() function results in an incremental error over time. This thus leads to the frame accuracy drifting.
UPDATE on 22/04/21
With the replacement of the playsound library with pygame , the error over time seemed to have been fixed. Though, further improvements and optimizations to the code can still be done. As of current, performance is still not optimal. A major bottleneck lies in the IOPS when dealing with the .txt files, am still trying to find a better implementation.
I am also looking into improving frame extraction and generation times.
UPDATE ON 23/04/21
It seems that frame extraction is heavily bottle-necked by the drive’s IOPS, and adding threads did not seem to expediate frame extraction further. I have created some rudimentary code for process-based and threading-based frame extraction, am looking to implement it for the ASCII generation soon.
UPDATE ON 25/04/21
I got about to implementing multi-processing for both frame extraction and ASCII generation. Though it seems that my implementation of threading/processing is still very botchy and thus asset generation is still sub-optimal. Not too sure on how far I would want to take this project, though my main priority right now would be to adjust frame timings.
SECOND UPDATE ON 25/04/21
Simply by replacing the primitive time.sleep() function with the fpstimer library, frame-time accuracy has been drastically improved, will be slowing down my code optimizations for playback from now onwards.
Though the main concern right now is trying to optimize asset generation times.
THIRD UPDATE ON 25/04/21
Changed the approach of storing assets. Should significantly reduce asset generation times, averaging arond 10
15 seconds using single thread. Will still look into threading to further expedite asset generation. However, with touhou_bad_apple_v4.0.py , progress will now slow down as I finally close the chapter of this project.
UPDATE ON 27/04/21
It looks like most of the issues have been rectified, and the code has reached desirableh performance. While I could further boost ASCII generation and add new functionality to the code, I feel that it would be over-engineering such a simple project. What started out as a weekend project blew up to such proportions, and led me to learn many new and interesting concepts along the way.
I really would like to thank JasperTecHK for his recommendations and suggestions along the way. His input was what really led me to return to this project after two dead weeks.
As such, major updates to the code would come much slower now, as the current iteration of the project has far exceeded my orginal goal. Though, it would be interesting to further develop v4.5 to have color support, but I would presume that requires its own development cycle. Once again, I really would like to thank all the contributors to this simple and dumb piece of code that I wrote in 24 hours.
Current known issues and bugs
Despite being a somewhat simple program, my crappy implementation has led to a lot of unresovled bugs and issues. I am currently looking at fixing some of them.
- block=False is not supported in Linux (Only for v2.0 and below)
I am currently trying to find alternatives to the playsound library. Using two different threads is not an option currently as I was running into desynchronization issues
This issue has been fixed in v3 v2.5, alongside other performance improvements.
- No such file or directory: ‘ExtractedFrames/BadApple_1.jpg’ (Only for v3.0 and v2.5)
Not really sure how this is happening, but will be looking into fixing it. I was unable to replicate the error but I assume it is due to my botchy implementation of file directories for the assets
Issue could be due to host machine not having ffmpeg installed. Ensure that you have ffmpeg installed and run the script again. v4 and v4.5 will not return this error, though will need to do some limit testing to figure it out.
First rudimentary version that accomplishes basic frame extraction and animation. Utilizes threads, but suffers from heavy synchronization issues.
Extended version that includes a «GUI», some basic file I/O. Suffers from slight synchronization issues. Core program logic was completed in 24 hours with some minor tweaks and comments afterwards.
- touhou_bad_apple_v3.py ==> Renamed to touhou_bad_apple_v2.5.py
Current development version. Improved frame time delay and better file I/O. Looking to implement threading to expedite frame extraction and ASCII conversion. Play-testing version to use py-game. Doesn’t really warrant a full version increment, will be updating the name to v2.5 or something like that once the new v4 is ready
Slightly better version due to incorporation of pygame for music playing. Rectifies issue when attempting to play on Linux based environments since the older playsound library did not support blocking=False on said environments.
Still has rudimentary frame extraction and ASCII generation on single thread/process, which makes asset generation significantly longer.
- touhou_bad_apple_v4.py ==> Renamed to touhou_bad_apple_v3.0.py
(Almost) re-written as the previous code was getting to messy to work with. Functions from previous versions are still used though.
Will be renamed to v3 once I improve asset generation times with better threading code. However, «v4» is currently the most frame-accurate version thanks to the fpstimer library. And subsequent changes are only for smaller performance optimizations.
Rewritten to incorporate multiprocess, though implementation is very janky. Overall program structure was also refactored a bit to clean up main() function. Asset generation times were reduced a bit, but the double for loop meant that it generation times are close to a minute.
- touhou_bad_apple_v4-5.py ==> Renamed to touhou_bad_apple_v4.0.py
Once again my dumb naming schemes kick in again. After some toying around, I decided to scrap the .txt file generation and skip right storing ASCII within memory. This version completely rewrites the asset generation algorithm. Instead of the old
Video => Extracted_Images (stored in storage) => ASCII Characters (stored in memory) => .txt (stored in storage)
process, ASCII generation is done on the image stored within memory, so
Video => Extracted_Images (stored in memory) => ASCII Characters (stored in memory) => Internal list (stored in memory)
Makes more sense as compared to older iterations and significantly cuts down asset generation times.
While this means that 10 or 20 seconds is required for ASCII generation, it eliminates storage IO bottleneck. Also frees up a lot of storage space on host system. Overall probably the best one yet?
- touhou_bad_apple_v5.py ==> Renamed to touhou_bad_apple_v4.5.py
Honestly I should not even get a job at file versioning. This version essentially allows the user to ASCII-fy any video provided that they have the video file in the root directory.
The main functions will be listed here.
Reads the files from the previously generated ASCII .txt files and prints it out onto the console.
Plays the bad apple audio track.
progress_bar(current, total, barLength=25)
A simple progress bar function that generates the status of both frame extraction and ASCII frame generation. This code was taken from a StackOverflow thread.
current is the current value/progress of the process.
total is the desired/intended end value of the process.
barLength=25 sets the length of the progress bar. (Default is 25 characters)
ASCII Frame generation
Not a particular function, but a group of functions.
These functions are called in the ascii_generator() function to convert image files to ASCII format and stores them into .txt files.
Note that the ASCII conversion code is not original, and was taken from here.
Words of acknowledgements
I should give credit where credit is due, and here is a section dedicated to that.
ZUN, and this incredible work on the Touhou project over the past decades.
Ronald Macdonald, for making the MIDI Arrangement of the Bad-Apple!! used.
GitHub users karoush1, JasperTecHK, TheHusyin, Mirageofmage for their comments and bugfixes.
About
Bad Apple printed out on the console with Python!
Источник