Blogs

How to write c++ programm for android (in Russian)
http://www.codeatcpp.com/2011/10/c-android-1.html


http://sivers.org/blog

How to make a movement


To translate:
Source: http://habrahabr.ru/post/206258/
2. Базар идей
В какой-то момент в нашей организации вошла в моду фраза «продать идею». Особенно активно я начал натыкаться на эти торги идеями с поднятием по карьерной лестнице, и имея частые совещания с теми, с которыми нас не связывали отношения подчинения. Фраза «продать идею» базируется на маркетинговом термине «sell idea», только понимание оного в проекции на организационную структуру было извращено. Если в оригинальном смысле продающий идею получает выгоду от тех, кто эту идею купил (инвесторы или заказчики), то в организационной структуре, продав идею, максимум можно было получить согласие купившего не мешать тебе ее реализовывать. А так как по такому выгодному курсу купить идею могут позволить себе даже неимущие, в итоге можно было потратить уйму времени, «продавая идею» тем, кто случайно оказался на совещании. Страдая на таких торгах, я часто задавался вопросом «зачем все эти люди?». Так у меня сложилось ощущение, что в одиночку сделать эту работу можно в разы быстрее, чем базаря на ярмарке идей.



А ведь правда, если можешь все сделать сам, зачем кого-то убеждать в том, что это надо делать?

Dear programmers, developers, architects and others!

In a new year please continue writting bad programs, make bugs, create bad architecture and so on! All this destroying activity provide infinite flow of well-paid job! Thanks to those people! Let's kludge together!

16 bit color formats

http://forums.creativecow.net/thread/2/940078

In adobe after effects:
#define PF_MAX_CHAN8			255
#define PF_HALF_CHAN8			128
#define PF_MAX_CHAN16			32768
#define PF_HALF_CHAN16			16384
#define CONVERT8TO16(A)		( (((long)(A) * PF_MAX_CHAN16) + PF_HALF_CHAN8) / PF_MAX_CHAN8 )

Import Sihlouette roto masks into several Nuke shapes

Today kids, I tell you how to split imported Sihlouette shapes into Nuke RotoPaint nodes.

In SihlouetteFX select several nodes.
Go File->Export->nuke 6.2+ Shapes  and save Nuke project

I tried to use also File->Export->Nuke Shapes but in Nuke 7.0 it wasn't opened properly

Open saved project in Nuke. There is a single RotoPaint node. It contains several layers with several shapes in each.
I need separate layers into many nodes to use them separately.

To do this I wrote following script:

Binarization in Adobe After Effects

I need to make binary image from grayscale one. I know I can use Levels filter for that with such settings:

Free open-source alternative to Total Commander

It seems I almost found alternative for TotalCommander.
Let me present DoubleCommander.
It is free, open-source, extendible by Total's plugins. That's awesome.
I also found out that viewer plugin SGView for TotalCommander can be  completely replaced by ImaginePlugin. Imagine has x64 version. The issue was to assign hotkeys like in SGView.

Books

In progress:
  1. The Black Swan: The Impact of the Highly Improbable -  Nassim Nicholas Taleb
  2. Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library Scott Meyers
  3. Learning Python, 5th Edition, 

---------------------------------------
Part
  1. Fooled by Randomness: The Hidden Role of Chance in Life and in the Markets - Nassim Nicholas Taleb
  2. Effective C++: 55 Specific Ways to Improve Your Programs and Designs Scott Meyers

---------------------------------------
Done
  1. Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma et al.
  2. C++ Coding Standards: 101 Rules, Guidelines, and Best Practices, Herb Sutter Andrei Alexandrescu
  3. C++: The Complete Reference, Herbert Schildt
  4. Testing Dot Com, or allowance for the abuse of bugs in Internet startups Roman Savin / Роман Савин - Тестирование DOT COM (in Russian)

По простому о matting laplacian

В математике у нас есть уравнение Лапласа
\delta u = 0
 Перепишем:

Вспомним, как можно расписывать вторую производную:

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

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



MATLAB


fmincor( ponter to target function, initial point, list of constrains) - some improved gradient decent. Step is adaptive.

useParallel - automatic parallel

Add backslash before all escape characters in python

Useful for using in regular expressions:

import re
re.escape( str )

Python detects all escape characters that can be used by regex  and add slash before them
http://docs.python.org/2/library/re.html#re.escape

Moving time indicator in composition timeline in After Effects CS6 using scripts

So, Javascript code for position changing is simple.
Lets say comp - is your composition:
precomp = app.project.items.addComp( "ololo", width, height, 1.0, duration, frameRate);
move pointer to time 0.2:
comp.time = 0.2;

То, что вы хотели знать про оптический поток, но стеснялись спросить

Взято с http://habrahabr.ru/post/201406/.
Объяснение оптического потока из OpenCV для тех, кто не в теме и не очень хочет разобраться.



Оптический поток (Optical flow) – технология, использующаяся в различных областях computer vision для определения сдвигов, сегментации, выделения объектов, компрессии видео. Однако если мы захотим его по-быстрому реализовать в своем проекте, прочитав про него на википедии или где-нибудь еще, то, скорее всего, очень быстро наткнемся на то, что он работает очень плохо и сбоит при определении сдвигов уже порядка 1-2 пикселей (по крайней мере так было у меня). Тогда обратимся к готовым реализациям, например, в OpenCV. Там он реализован различными методами и совершенно непонятно, чем аббревиатура PyrLK лучше или хуже обозначения Farneback или чего-нибудь в этом роде, да и придется поразбираться со смыслом параметров, которых в некоторых реализациях очень много. Причем, что интересно, эти алгоритмы как-то работают, в отличие от того, что мы написали сами. В чем же секрет?

OpenCV tutorials (Russian)


1. Делаем детектор движения, или OpenCV — это просто
http://habrahabr.ru/company/avi/blog/200804/
2. OpenCV шаг за шагом
http://robocraft.ru/blog/computervision/265.html
3. Пару слов о распознавании образов
http://habrahabr.ru/post/208090/

Building opencv program in C

gcc -ggdb `pkg-config --cflags opencv` -o `basename test.c .c` test.c `pkg-config --libs opencv`
Description:`pkg-config --cflags opencv` — подставляет путь для инклудов через pkgconfig.
`pkg-config --libs opencv` — подставляет название либ для линковки через pkgconfig.
При установке opencv поместила файлик .pc (в моём случае это /usr/lib/pkgconfig/opencv.pc), в котором рассказывается, где находятся заголовочные файлы этой библиотеки, а где сами либы для линковки. Таким образом первое у меня разворачивается в "-I/usr/include/opencv", а второе — в "-lopencv_calib3d -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_objdetect -lopencv_ocl -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_video -lopencv_videostab", т.е. уже в прямые указания компилятору и линкеру, где искать инклуд-файлы (-Include) и библиотеки (-library), позволяющие разработчику не вбивать всё это руками.
-o `basename test.c .c` — отрезает от test.c часть с расширением (".c"), оставляя только часть имени файла «test», которое будет являться именем выходного (output) собранного исполняемого файла. Т.е. разворачивается это в "-o test".
-ggdb — смотрим в ман (а стоило бы сделать это ещё в начале ;))
-ggdb
Produce debugging information for use by GDB. This means to use the most expressive format available (DWARF 2, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible.

т.е. генерация максимально полной отладочной информации для использовании в отладчике gdb (и включение её в выходной бинарник, например замечены секции .debug_aranges, .debug_info, .debug_abbrev, .debug_line, .debug_str).

Blog about computer vision and opencv
http://www.uralvision.blogspot.ru/

Free UML editor

I found free UML editor:

ArgoUML http://argouml.tigris.org/

It seems not bad



I have tried gliffy.com. It is online and paid.
www.lucidchart.com has free version but it seems not so convenient

How to open composition in viewer in Adobe After Effects using scripts

// Make a composition
var comp = app.project.items.addComp('MyComp', 1920, 1080, 1.0, 10, 25.0 );

// Open it in viewer
comp.openInViewer();

This solution works only in AAE CS 6.0

My version of some cross-platform code

function OpenInViewer( comp )
{
    var version = app.version.match(/(\d+\.\d+).*/)[1];

    if( version >= 11.0 )
        comp.openInViewer() ;
    else
    {
        var duration = comp.workAreaDuration;
        comp.workAreaDuration = 2*comp.frameDuration;
        comp.ramPreviewTest("",1,"");
        comp.workAreaDuration = duration;
    }

}

inspired by http://www.videocopilot.net/forum/viewtopic.php?f=5&t=116057#p348646

Convert all *.avi files in current directory to png sequences

Using python and ffmpeg:

#!/usr/bin/python
# -*- coding: cp1251 -*-

import glob
import os

t=glob.glob("*.avi" ) # search all AVI files

for v in t:
     vv = os.path.splitext(v)[0];
     os.makedirs( vv ) # make a directory for each input file
     pathDst = os.path.join( vv, "%05d.png" ) # deststination path

     os.system("ffmpeg -i {0} {1}".format( v, pathDst ) )

Print all commands that were entered in interactive mode in Python

import readline
readline.write_history_file( "log.py")

Десятка лучших консольных команд

Взято с хабра: http://habrahabr.ru/post/198482/


imageВ данном посте я расскажу о наиболее интересных командах, которые могут быть очень полезны при работе в консоли. Однозначных критериев определения какая команда лучше другой — нет, каждый сам для своих условий выбирает лучшее. Я решил построить список команд на основе наиболее рейтинговых приемов работы с консолью от commandlinefu.com, кладовой консольных команд. Результат выполнения одной из таких команд под Linux приведен на картинке. Если заинтересовало, прошу под кат.

Десятое место

Ввод последнего аргумента недавних команд. Удерживая ALT или ESC, с каждым нажатием на точку в строку ввода будут подставляться параметры предыдущих команд, начиная от недавно введенных к старым.
Комбинация 'ALT+.' или '<ESC> .'

Девятое место

Переинициализация терминала без завершения текущей сессии. Например, в случае когда в терминал были выведены двоичные данные и он перестал корректно работать.
reset

Восьмое место

Создает пустой файл. Уничтожает содержимое файла без его удаления.
> file.txt

Седьмое место

Запуск команды с пробелом перед ней не сохраняет ее в истории. Может пригодиться при передаче паролей программам в открытом виде.
<пробел>команда

OpenCV. Processing external byte buffer



We have such an example from openCV documentation:
Mat img(height, width, CV_8UC3, pixels, step);
GaussianBlur(img, img, Size(7,7), 1.5, 1.5);

What does it mean? 
Lets say I have an image img:
typedef unsigned char BYTE;
BYTE * img = new BYTE[ w * h ];
Lets assume the image is scanned line by line. So
img[ 10 * w + 3 ] is a 3-rd pixel in 10-line of image.
Then I import it in openCV is such a way:
Mat img(h, w, CV_8UC1, dmDst, w);

last argument is a pitch or stride.












Fast way of copying byte array in C/C++ (With measurements)

I have the following code for copying several buffers from one object to another:
// Copy several buffers (images)
for( int i = 0; i < MIN( conf_.size(), src.conf_.size() ); ++ i )
{
   // Copy one image per pixel
   for( int j = 0; j < MIN( sizeOfBuffer_, src.sizeOfBuffer_ ); ++ j )
   {
      conf_[i][j] = src.conf_[i][j];
   }
}


Array conf_ is defined as follows:
std::vector<BYTE*> conf_;

BYTE is unsigned char. That code is written with no doubt about software performance. It just works. When I do so I hope compiler make it better for me.
This fragment takes about 45 ms for copying of 2 images with ( 1980x1080 pixels ) x 3 planes = 6.2 MPixels.
I use Microsoft Visual Studio 2008 compiler on Intel Core i7 950 @ 3.07 GHz. The code is built for x64 platform. Disabled compiler option for buffer security check (GS-) and debug information has no effect on the productivity.

Slightly better solution:
// Copy several buffers (images)
for( int i = 0; i < MIN( conf_.size(), src.conf_.size() ); ++ i )
{
   int sizeOfArray = MIN( sizeOfBuffer_, src.sizeOfBuffer_ );

   // Copy one image per pixel
   for( int j = 0; j < sizeOfArray; ++ j )
   {
      conf_[i][j] = src.conf_[i][j];
   }
}
It takes about 35 ms per full copy.

Much better solution:

How to cheat on video encoder comparisons

Source:Diary Of An x264 Developer

Over the past few years, practically everyone and their dog has published some sort of encoder comparison.  Sometimes they’re actually intended to be something for the world to rely on, like the old Doom9 comparisons and the MSU comparisons.  Other times, they’re just to scratch an itch — someone wants to decide for themselves what is better.  And sometimes they’re just there to outright lie in favor of whatever encoder the author likes best.  The latter is practically an expected feature on the websites of commercial encoder vendors.
One thing almost all these comparisons have in common — particularly (but not limited to!) the ones done without consulting experts — is that they are horribly done.  They’re usually easy to spot: for example, two videos at totally different bitrates are being compared, or the author complains about one of the videos being “washed out” (i.e. he screwed up his colorspace conversion).  Or the results are simply nonsensical.  Many of these problems result from the person running the test not “sanity checking” the results to catch mistakes that he made in his test.  Others are just outright intentional.
The result of all these mistakes, both intentional and accidental, is that the results of encoder comparisons tend to be all over the map, to the point of absurdity.  For any pair of encoders, it’s practically a given that a comparison exists somewhere that will “prove” any result you want to claim, even if the result would be beyond impossible in any sane situation.  This often results in the appearance of a “controversy” even if there isn’t any.
Keep in mind that every single mistake I mention in this article has actually been done, usually in more than one comparison.  And before I offend anyone, keep in mind that when I say “cheating”, I don’t mean to imply that everyone that makes the mistake is doing it intentionally.  Especially among amateur comparisons, most of the mistakes are probably honest.
So, without further ado, we will investigate a wide variety of ways, from the blatant to the subtle, with which you too can cheat on your encoder comparisons.


Using h264/multiview codec from Intel Media SDK

I needed to launch multiview compression using codec from Intel MVC. Approximately a half a year ago I launched it normally. Yesterday it tried and I got such an error:

$ ./sample_encode.exe h264 -i input.yuv -o output.h264 -w 1920 -h 1080
Return on error: error code -3, .\src\pipeline_encode.cpp       865

Return on error: error code 1,  .\src\sample_encode.cpp 343
Frame number: 0
I started debug and found out the error appears in 
MFXVideoSession::mfxStatus Init(mfxIMPL impl, mfxVersion *ver)
{
    return MFXInit(impl, ver, &m_session);
}
Error code
 MFX_ERR_UNSUPPORTED                 = -3,   /* undeveloped feature */

Of course, the cause was in missing dll.
libmfxsw32.dlllibmfxsw64.dll
After I added it to console's directory everything became fine.


PS I could not build sample_encode with Visual Studio 2008. So use 2010 instead.

Using ls command

ls -w1 */  - show only subdirectories in current directory (*/) and display in 1 column (-w1)
ls -c  - sort by date

Некоторые заметки о приведении типов в СиПлюсПлюс

АлёнаC++:
http://alenacpp.blogspot.ru/2005/08/c.html

static_cast между указателями корректно, только если один из указателей - это указатель на void или если это приведение между объектами классов, где один класс является наследником другого. То есть для приведения к какому-либо типу от void*, который возвращает malloc, следует использовать static_cast.
int * p = static_cast<int*>(malloc(100));
Если приведение не удалось, возникнет ошибка на этапе компиляции. Однако, если это приведение между указателями на объекты классов вниз по иерархии и оно не удалось, результат операции undefined. То есть, возможно такое приведение: static_cast<Derived*>(pBase), даже если pBase не указывает наDerived, но программа при этом будет вести себя странно.

Math morphology in Adobe After Effects

Errosion and dilation in AE is implemented in Minimax filter. See settings bellow:

Opencv and "OpenCV Error: Bad flag"


   
I had pretty simple code with opencv:

    cv::Mat t;
    t = cv::imread( "qq.bmp" ) ;
    cv::imwrite( "q.bmp", t );
    cv::namedWindow( "asdads", CV_WINDOW_AUTOSIZE );
    cv::imshow( "asdads", t );
    cv::waitKey( -1 );
    return 0;

It caused crash in debug configuration:

OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupport
ed array type) in unknown function, file ..\..\..\src\opencv\modules\core\src\ar
ray.cpp, line 2482

In release configuration it was ok. Finally i found the solution. Both in debug and release configurations I used static libraries for release conguration

opencv_core231.lib opencv_imgproc231.lib opencv_highgui231.lib

And one should use
opencv_core231d.lib opencv_imgproc231d.lib opencv_highgui231d.lib
for debug.

It seems wrong libraries cause crashes only sometimes. I had used release version of static opencv libraries for my debu and release configurations for a long time an only now it caused problems


OpenCV. Copy image from unsigned char buffer, resize and save to file

How to copy image from unsigned char buffer, resize and save to file.
If you use single-channel image.

#include <opencv/cv.h>
#include <opencv/highgui.h>

                int coeff = 4;
                cv::Mat src( height, width, CV_8UC1, (void *) source_byte_beffer ) );
                cv::Mat small(height/ coeff, width/ coeff, CV_8UC1 );

                cv::Size s_half(width/ coeff, height/ coeff);
                cv::resize( src, small, s_half, 1, 1, cv::INTER_LINEAR ); // resize from src to small

                IplImage* writeImage;
                writeImage=cvCloneImage(&(IplImage)src);
                cvSaveImage("src1.bmp", writeImage);
                cvReleaseImage( &writeImage );

                writeImage=cvCloneImage(&(IplImage)small);
                cvSaveImage("little.bmp", writeImage);
                cvReleaseImage( &writeImage );


                //Another way of writtting:               
                /*cvWrite("src.bmp", src );
                cv::imwrite( "small.bmp", small );*/

                
         

SVN copy certain subdirectories to a branch

There was always a problem for me to copy only certain directories from one branch to another.
For example we have following directory structure:
trunk
      - project1
      - project2
          -subdir1
          -subdir2
          -subdir3        
We want to copy only subdir2 to a branch /branches/branch1 with saving all the structure of projects.
branches/branch1
      - project1
      - project2
          -subdir2
We want to copy only subdir2 to a branch /branches/branch1 with saving all the structure of projects.
Such a manipulation is required if you want to make a private branch for outsorcer and you don't wan him to see the other parts of the code. However you want to support reintegration of the branch back to the trunk.

The solution is 
svn cp --parents ./project2/subdir2 http://repo.url/branches/branch1/project2/subdir2
or
svn cp --parents http://<svn_path>/trunk/project2/subdir2 <working copy path>/branches/branch1/project2/subdir2
Subversion creates all intermediate directories.

Trim frames from raw YUV video using FFMPEG

Trim 5 frames starting from 160-th frame and write to png sequence

ffmpeg -pix_fmt yuv420p -s 1920x1088  -r 1 -i input_video.yuv -r 1 -ss 160 -frames 5  output_sequence_%d.png

size of input video is 1920x1088, format YUV420 progressive

UPD:
ffmpeg is renamed to avconv.
Using it for trimming AVI video:

avconv -ss 00:58:00 -t 00:59:30 -i ./video.avi frame_%05d.png

Color problems in avisynth->overlay

I processed depth maps using avisynth 2.5.8 and I found out it causes color degradation

I have a depth map (from http://vision.middlebury.edu/stereo/data/scenes2001/data/imagehtml/sawtooth.html)

And two scripts
1) just_show.avs
v = ImageSource( "depth.jpg" ).Trim(0, -1)
return v
2) overlay.avs
v = ImageSource( "depth.jpg" ).Trim(0, -1)
return overlay( v, v, mode = "blend", opacity = 0.80) 

They have slightly different colors.
just show


overlay

Overlay has chroma component
The cause was in wrong color conversion in avisynth 2.5.8. I downloaded AVS 2.6.0 Alpha 4 [130114] and the problem gone. http://sourceforge.net/projects/avisynth2/files/AviSynth_Alpha_Releases/AVS%202.6.0%20Alpha%204%20%5B130114%5D/

Add path in linux/cygwin and windows

Add path in cygwin /linux
PATH=$PATH:~/your_path
PATH=~/your_path:$PATH

Add path windows
PATH=%PATH%;C:\Your_Path;

Never never!

Never-Never-NEVER open file for reading until you think twice what mode (text/binary) of operation do you need!!

How to compare video metrics

There are specific databases which were subjectively tested. Ans MOS was calculated
for example
http://www.ponomarenko.info/tid2008.htm
you can download database and compare your metric to MOS by Spearman correlation

SSIM metric for video

See good explanation is in

Title: Handbook of image and video processing 
Author(s): Bovik A. (ed.)
Series: Periodical:
Publisher: Elsevier Academic Press 
Year: 2005 
Edition: 2ed.
Language: English 
Pages: 1429
ISBN: 9780121197926, 0121197921

SSIM по русски

Нужно будет тут записать как работает метрика SSIM по человечески

Replace \n in Microsoft word

To replace new lines in word use "^13" whild-char. "^p" doesn't work :(

Tips for debugging of video processing console

Assume we have Visual Stusio solution for console that makes some video processing.
The console takes two input videos and generates the third video:
Console.exe --input1 video1.avi --input2 video2.avi --output result.avi
While debugging we need to run console on several datasets.
1) dataset1 conststs of videos set1_video1.avi and set1_video2.avi
2) dataset2 conststs of videos set2_video1.avi and set2_video2.avi
....
n) ....

It seem rather convenient to distrubute videos between folders. One folder for each dataset. Insise the folder we should give template names to files (e.g. video1.avi and video2.avi)
Therefore now we can set "Command Arguments" in "Project Properties->Configuration properties->Debugging" the same arguments for all cases and configurations,
The thing should vary is "Working directory" in "Properties->Configuration properties->Debugging".


Another usefull thing is setting  "Environment". Just write there
PATH=%PATH%;<path to dll>
and you don't need to copy all dependency dll's in every debug folder. 

Bjontegaard metric. Matlab script.



Bjontegaard metric (BD-PSNR) describes the distance between two RD-curved. I is useful to determine how big is the gain between "before" and "after" versions. Or determine what curve is better if they have complex form (for example, intersecting).

I found matlab script, that calculates BD-PSNR, but it was not correct. The limits of integration were wrong. Difference between two curves can be calculated only in the area of thein projections intersection.
Fixed script was verified by data provided the auther of the metric.

Download
fixed matlab script for BD-PSNR calculation
github
original paper (doc)
data for verification (xls)



Original publilcation:
G. Bjontegaard, “Calculation of average PSNR differences between RD-curves (VCEG-M33),” in
VCEG Meeting (ITU-T SG16 Q.6), Austin, Texas, USA, Apr. 2001

Problems with debug run from Visual Studio with openMP

I had a problem while running debug+openmp configuration of my console. Meanwhile in Release+openmp configuration everything is ok. Diagnostic message I see is something about wrong parallel configurations, system log and sxstrace.exe.

The solution is following.
Folder
Microsoft.VC90.DebugOpenMP
with files
Microsoft.VC90.DebugOpenMP.manifest
vcomp90d.dll 
were missing. I knew this problem for the folder I specify in debug properties in visual studio:
In that folder I already had Microsoft.VC90.DebugOpenMP. But to avoid error I should place it in output directory (where my binary exe file is placed):

Magick...

Another place with boost binaries

http://boost.teeks99.com/ - Another place with boost binaries. It includes build for version 1.49

Before I new only http://www.boostpro.com/download/

Error spawning cmd.exe

I got error message 
Error spawning cmd.exe
during compiling of Blender sources.
The cause was in system PATH environment variable. Some buggy software I had installed and uninstalled before erased all contents of PATH. So I found out that Visual Studio 2008 has missing paths to
%SystemRoot%\system32;
%SystemRoot%;
%SystemRoot%\System32\Wbem;
A added it and the problem gone. 

Blogs about blender

Overview of open-source node-based video editors (composers)

Synapse Compositor

Seems unsupported for a long time
Very raw






Blender

Good staff, but it is designed originally for 3D modeling. Video editing is performed in composing mode. Rendering is veeery sloooowww. Open source. Available for linux and windows.
Source code: http://gitorious.org/blenderprojects/

Image resize in Nuke

So here we have two filters:
1) Crop
2) Reformat

To cut a part from an image we use Crop. It also has option "reformat". Reformat cuts also borders behind area. If "Reformat" is disabled, black borders remain after crop.