Concatenate two images in the channel dimension?
I have to concatenate two images in the channel dimension in either MATLAB or Python.
Let's say we take two grayscale input images, where each has for example the dimension [1, 1, 28, 28]
(i.e. 1 image, 1 channel, 28x28 resolution). How can we concatenate them to be one image of size [1, 2, 28, 28]
?
3 answers

I'm not sure what you want to do with your fist dimension but this works for your example:
img1 = randi(255,1,1,28,28); % first image img2 = randi(255,1,1,28,28); % second image img1(1,end+1,:,:) = img2; % stack second image on top of first image size(img1) % [ 1 2 28 28]

In MATLAB you would usually use the
cat
command for this:bigMat = cat(dimNo, matA, matB); % dimNo can be 1, 2, ...
But in the case of concatenating along the 2^{nd} dimension, you can also simply use
[... ; ...]
:bigMat = [matA; matB];
(which is equivalent to the
vertcat
function).If you know in advance how many matrices you'd like to concatenate (i.e. the final size of the result), you should preallocate your matrix using e.g.
bigMat = zeros(1, N, 28, 28)
, then put each image in its correct position similarly to the previous answer img1(:,n,:,:) = img2; % where n is 1..N, and not anything like end+1
We don't want to use
end+1
as this incurs performance losses related to constant reallocation of larger and larger arrays and copying all contents of the array each time. 
Python: Use numpy for this operation:
import numpy as np img1, img2 = np.random.rand(1,1,28,28), np.random.rand(1,1,28,28) img = np.concatenate([img1, img2], axis=1)
The argument
axis=1
defines the axis along which the operation is executed.
See also questions close to this topic

Showing all the images with matplotlib
I'm using numpy and matplotlib to read all the images in the folder for image processing techniques. Although, I have done the part of reading image dataset from folders and process it with numpy array. But the problem, I'm facing is of showing all the images with matplotlib.imshow function. Everytime I want to show all the images with imshow function, unfortunately it just give me first image nothing else. My code is below:
import os import numpy as np import matplotlib.pyplot as mpplot import matplotlib.image as mpimg images = [] path = "../path/to/folder" for root, _, files in os.walk(path): current_directory_path = os.path.abspath(root) for f in files: name, ext = os.path.splitext(f) if ext == ".jpg": current_image_path = os.path.join(current_directory_path,f) current_image = mpimg.imread(current_image_path) images.append(current_image) for img in images: print len(img.shape) i = 0 for i in range(len(img.shape)): mpplot.imshow(img) mpplot.show()
I will be thankful if somebody can help me in this.
P.S. I'm pretty new with python, numpy and also at stackoverflow. So, please don't mind if the question is unclear or not direct.
Thanks,

Tkinter, changing a button and its command
We have a button that calls function A. We want function A to change the image of that button and to change its command to call function B instead of A. How to do that? We can't have two buttons at the same time.
Thank you in advance.

SYN flooding in Python
Is there any way to perform SYN flooding on a target ip address? I have tried many programs but none of them have seem to flood the targeted ip addresses. Kindly help.

images not appearing online but appears offline. I am uploading via Filezilla
I am uploading my website using Filezilla, and some images are not appearing. I have checked that the file names are all lower case and that the file type is set to auto instead of ASCII. I have cleared the cache too and I am still not seeing the same images not appearing.
I have got a 403 and 404 error on these images in the console, please see screenshot image for this.error image
All images work fine when testing locally on my computer but some random images are not appearing. Anyone any ideas why this could be?
Thanks!

Image Streaming using QGraphicsView
I am trying to display images from a CameraLink Camera into a QGraphicsView. I am using a ring buffer which get() and set() functions and two threads that consume or produce the images in this ring buffer. This part works because I already had a successfull streaming using a QWidget. I want to use a QGraphicsView because I want to draw over those incoming images
I have a display class which is promoted to QGraphicsView, everytime an image is produced, a signal is emitted from the consumer thread to the following function:
void display::drawImage(ImageBW* image) { firstImage = image; QRect rect; rect.setHeight(1000); rect.setWidth(2000); QApplication::postEvent(this>viewport(),new QPaintEvent(rect)); }
I have reimplemented the painEvent of the QGraphicsview class:
void display::paintEvent(QPaintEvent *event) { if(firstImage) _drawImage(); event>setAccepted(true); }
and the drawing function is:
void display::_drawImage() { int w, h; if(img) { delete img; img = NULL; } w = firstImage>getSizeX(); h = firstImage>getSizeY(); unsigned char * udata = (unsigned char *)firstImage >getData(); img = new QImage(udata,w, h,QImage::Format_Grayscale8); pix_img = QPixmap::fromImage(*img); scene>clear(); scene>addPixmap(pix_img); scene>setSceneRect(pix_img.rect()); scene>update(); update(); // I have tried here also setScene(scene) }
In the above code, firstImage is an ImageBW* variable. ImageBW is where the image data from camera is stored.
I have also tried with QGraphicsItem and addItem() function but i get no Image. 'scene' is initialized on the producer of this class and also the 'setScene(scene);' command is there. The program stucks after a while so that probably means that this code produces stackoverflow. Please I have tried everything i can think of, any help would be greatly appreciated.
Thanks in advance

RGB pixelation using c language
I'm trying to write a pure c code to implement mean filter pixelation.
size
denotes the size of filter.p
denotes padding, which will be added automatically when image is brought to memory to align width of memory to multiple of 4 bytes. My code below hasn't yet taken into account that it will be used to R, G, B. It's written to be applied to the first 8 bits of each 24 bits RGB block.I have classified the case into 3, where the image pointer is at the end of each row / is at the last row / and all the other normal cases. I'm moving the image pointer along to move the filter to next pixel position and changing the value of original image array to average of the values inside the filter.
It gives me a segmentation fault error consistently,
problem arising from
val+=*(imgptr + 3 * l + (3 * width + p)*k)
.Can't think of solutions, need your ideas... Thanks
void pixelate(unsigned char *imgptr, long long width, long long height, long long size) { long long last_w; long long last_h; long long m = width / size; if ((width%size) == 0) last_w = size; else { m++; last_w = width % size; } long long n = height / size; if (height%size == 0) last_h = size; else { n++; last_h = height % size; } int p = 4  ((3 * width) % 4); //padding size for (long long i = 0; i < m*n; i++) { long long val = 0; if (i >= m * (n  1)) { if (i == m * n  1) { for (long long k = 0; k < last_h; k++) { for (long long l = 0; l < last_w; l++) { val += *(imgptr + 3 * l + k * (3 * width + p)); } } val /= (last_h*last_w); //getting average for (long long k = 0; k < last_h; k++) { for (long long l = 0; l < last_w; l++) { *(imgptr + 3 * l + k * (3 * width + p)) = val; } } return; } else { for (long long k = 0; k < last_h; k++) { for (long long l = 0; l < size; l++) { val += *(imgptr + 3 * l + k * (3 * width + p)); } } val /= (last_h*size); for (long long k = 0; k < last_h; k++) { for (long long l = 0; l < size; l++) *(imgptr + 3 * l + k * (3 * width + p)) = val; } imgptr += 3 * size; continue; } } else if (i%(m1) == 0) { for (long long k = 0; k < size; k++) { for (long long l = 0; l < last_w; l++) { val+=*(imgptr + 3 * l + (3 * width + p)*k); } } val /= (size*last_w); for (long long k = 0; k < size; k++) { for (long long l = 0; l < last_w; l++) *(imgptr + 3 * l + (3 * width + p)*k) = val; } imgptr += p; continue; } else { for (long long k = 0; k < size; k++) { for (long long l = 0; l < size; l++) val+=imgptr[3 * l + (3 * width + p)*k]; } val /= (size * size); for (long long k = 0; k < size; k++) { for (long long l = 0; l < size; l++) *(imgptr + 3 * l + (3 * width + p)*k)=val; } imgptr = imgptr  (3*width+p)*(size1) + 3; continue; } } }

Genetic Algorithm matlab in python with DEAP
I'm trying to translate a matlab function into python... but now at some point matlab uses internal functions that I don't know how to run on python
this is the section of matlab code:
options = optimoptions(@ga,'PopulationSize',100); [x,fval] = ga(FitnessFunction,numVar,A,b,[],[],lb,ub,[],options);
the disp of options in matlab is:
Set properties: PopulationSize: 100 Default properties: ConstraintTolerance: 1.0000e03 CreationFcn: @gacreationuniform CrossoverFcn: @crossoverscattered CrossoverFraction: 0.8000 Display: 'final' EliteCount: '0.05*PopulationSize' FitnessLimit: Inf FitnessScalingFcn: @fitscalingrank FunctionTolerance: 1.0000e06 HybridFcn: [] InitialPopulationMatrix: [] InitialPopulationRange: [] InitialScoresMatrix: [] MaxGenerations: '100*numberOfVariables' MaxStallGenerations: 50 MaxStallTime: Inf MaxTime: Inf MutationFcn: {@mutationgaussian [1] [1]} NonlinearConstraintAlgorithm: 'auglag' OutputFcn: [] PlotFcn: [] PopulationType: 'doubleVector' SelectionFcn: @selectionstochunif UseParallel: 0 UseVectorized: 0
How do I translate this into python? maybe using deap thanks thanks

C and MATLAB: Create empty array in C calls Matlab function to fill it ends in error
This is the problem:
I have a C code that creates an array
nRows x 2
, calledInitialArray
filled with random numbers. Then I split that array into two parts, that is the first column is calledxProcess
and the second column of the array isyProcess
. The goal is to pass these variables I created (xProcess
andyProcess
) to Matlab and there a Matlab function based on probabilities rules will putNaN
in some of the elements ofxProcess
andyProcess
, and will fill empty arrays calledxC
andyC
with the values ofxProcess
andyProcess
before turning toNaN
. Finally, the C code gets all four arrays back again, perform some operations on them and send them again to Matlab. This process is repeated for a number of time steps.Here is a piece of the code:
int main ( void ){ Engine *ep; if (!(ep = engOpen(""))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } mxArray *xProcess = NULL; mxArray *yProcess = NULL; mxArray *xC = NULL; mxArray *yC = NULL; int timeStep; int numberProcess = 4e6; int numberC = 0;
So far I created the mxArray, and the number of random numbers that will be stored in
xProcess
andyProcess
. Now comes the loop.for (timeStep=0 ; timeStep<numberTimeSteps ; timeStep++){ double *arrayTempxProcess; arrayTempxProcess = (double *)calloc(numberProcess, sizeof(double)); double *arrayTempyProcess; arrayTempyProcess = (double *)calloc(numberProcess, sizeof(double)); double *arrayTempxC; arrayTempxC=(double *)calloc(numberC, sizeof(double)); double *arrayTempyC; arrayTempyC=(double *)calloc(numberC, sizeof(double)); xProcess = mxCreateDoubleMatrix(numberProcess, 1, mxREAL); yProcess = mxCreateDoubleMatrix(numberProcess, 1, mxREAL); xC = mxCreateDoubleMatrix(numberC, 1, mxREAL); yC = mxCreateDoubleMatrix(numberC, 1, mxREAL); memcpy((void *)mxGetPr(yProcess), (void *)arrayTempyProcess, numberProcess*sizeof(double)); memcpy((void *)mxGetPr(xProcess), (void *)arrayTempxProcess, numberProcess*sizeof(double));
As you see
xC
andyC
I create them as empty. I believe this is equivalent toxC = []
andyC = []
in Matlab. And thearrayTempyProcess
andarrayTempxProcess
are temporal arrays that each of them gets a column ofInitialArray
.if(timeStep>0){ memcpy((void *)mxGetPr(yC), (void *)arrayTempyC,(numberC)*sizeof(double)); memcpy((void *)mxGetPr(xC), (void *)arrayTempxC, (numberC)*sizeof(double)); }
Now I send them to Matlab
engPutVariable(ep, "xProcess", xProcess); engPutVariable(ep, "yProcess", yProcess); engPutVariable(ep, "xC", xC); engPutVariable(ep, "yC", yC); free(arrayTempxProcess); free(arrayTempyProcess); free(arrayTempxC); free(arrayTempyC);
Now the Matlab function puts
NaN
inxProcess
andyProcess
, and fillsxC
andyC
.printf("Entering MATLAB \n"); engEvalString(ep, "[xProcess,yProcess,xC, yC] = my_matlab_function(xProcess,yProcess,xC, yC);"); printf("Leaving MATLAB \n");
Now comes trouble... Now I am trying to get the results... but the function
mxGetM(xC)
produces a segmentation fault in the first time step that I don't understand.xC = engGetVariable(ep,"xC"); int mRowsC = mxGetM(xC); double *XC = NULL; XC = (double *)malloc (mRowsC*sizeof(double) ); memcpy(XC, mxGetData(xC),mRowsC*sizeof(double)); yC = engGetVariable(ep,"yC"); double *YC = NULL; YC = (double *)malloc (mmy*sizeof(double) ); memcpy(YC, mxGetData(yC),mmy*sizeof(double)); xProcess = engGetVariable(ep,"xProcess"); int mRowsProcess = mxGetM(xProcess); double *XPROCESS = NULL; XPROCESS = (double *)malloc (mRowsProcess*sizeof(double) ); memcpy(XPROCESS, mxGetData(xPROCESS),mRowsProcess*sizeof(double)); yProcess = engGetVariable(ep,"yProcess"); double *YPROCESS = NULL; PROCESS = (double *)malloc (mRowsProcess*sizeof(double) ); memcpy(YPROCESS, mxGetData(yProcess),mRowsProcess*sizeof(double)); numberC = mRowsC; mxDestroyArray(xProcess); mxDestroyArray(yProcess); mxDestroyArray(xC); mxDestroyArray(yC); free(XPROCESS); free(YPROCESS); free(XC); free(YC); } }
I have tried to reduce the number of elements in
xProcess
andyProcess
but I get the segmentation fault at some point later than the first time step. The weird thing about this, is that I also tried to save the results in Matlab afterprintf("Leaving MATLAB \n");
but it didn't work out. It saved nothing.I'm new coupling C and Matlab, so my code might be entirely wrong, but is there any limits in which C cannot be coupled with Matlab functions?
Any help is appreciated. Thanks!

Solving a system of ODEs and one PDE with bvp4c
knowing that bvp4c is based on Finite Differences, would it be possible to solve a system of ODEs containing also one PDE? Thank you.

How to Convert Binary file to 2d matrix IN PIG Scripts
I am new in pig , Please Help in this .
Problem is :
i have a binary file those size is apporox 700mb .
and in this file there is 164byts of elment present...here one element = 1byte
how to create this flat file into 2d matrix in pig script to load the

std::bad_alloc in Gaussian Elimination written based on a pseudocode
I used this pseudocode:
h := 1 /* Initialization of the pivot row */ k := 1 /* Initialization of the pivot column */ while h ≤ m and k ≤ n /* Find the kth pivot: */ i_max := argmax (i = h ... m, abs(A[i, k])) if A[i_max, k] = 0 /* No pivot in this column, pass to next column */ k := k+1 else swap rows(h, i_max) /* Do for all rows below pivot: */ for i = h + 1 ... m: f := A[i, k] / A[h, k] /* Fill with zeros the lower part of pivot column: */ A[i, k] := 0 /* Do for all remaining elements in current row: */ for j = k + 1 ... n: A[i, j] := A[i, j]  A[h, j] * f /* Increase pivot row and column */ h := h+1 k := k+1
To write this code (Gaussian Elimination):
#include <iostream> #include <vector> #include <algorithm> #include <cmath> typedef std::vector<std::vector<int>> matrix; typedef long long ll; void inverse_matrix(matrix &mat) { ll h = 1, k =1; auto m = mat.size(), n = mat[0].size(); while (h <= m && k <= n) { ll i_max = 0; for (ll i = h; i <= m; ++i) { i_max = std::fmax(i, std::abs(mat[i][k])); } if (mat[i_max][k] == 0) { ++k; } auto temp = mat[h]; mat[h] = mat[i_max]; mat[i_max] = temp; for (auto j = h + 1; j <= m; ++j) { auto f = mat[j][k] / mat[h][k]; mat[j][k] = 0; for (auto v = k + 1; v <= n; ++v) { mat[j][v] = mat[j][v]  mat[h][j] * f; } } ++h; ++k; } } int main() { matrix mat = {{2, 2}, {4, 5}}; inverse_matrix(mat); return 0; }
But I get this error:
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
What's wrong? I copied the pseudocode to a tee.

Subtract a column vector from matrix at specified vector of columns using only broadcast
I want to subtract a column vector from a numpy matrix using another vector which is index of columns where the first column vector needs to be subtracted from the main matrix. For eg.
M = array([[ 1, 2, 1, 1], [ 2, 1, 1, 1], [ 1, 1, 2, 1], [ 2, 1, 1, 1], [ 1, 1, 1, 2]]) # An example matrix V = array([1, 1, 1, 1, 1]) # An example column vector I = array([0, 3, 2, 3, 1, 3, 3]) # The index maxtrix
Now I want to subtract V from M at column numbers given in I. For eg. I[0] is 0, so subtract V from first column (zero index) of matrix M.
Similarly I[1] = 3, subtract V from fourth column (three index) of matrix M.
At the end of operation, since 3 occurs 4 times in I, so V will be subtracted from third column i.e. last column of M 4 times.
I need to do this using only broadcast, no loops.
I have tried the following:
M[:, I]  V[np.newaxis, :].T
but it ends up broadcasting resultant matrix to have more columns than there are in M.

How to use Concat in a where clause in MYSQL?
I am trying to collect all the names with an extension at the end of a string in MYSQL.
Table1
ID  Name 0 Bob 1 1 Bob 2 2 Joe 1 3 Joe 2 4 Bob 5 Joe
The query I'm running is similar to this one:
SELECT ID, name FROM Fname WHERE name = CONCAT(name,' ','1');`
Where I want to collect all the Names that end it a space and 1.

pandas aggregating frames by largest common column denominator and filling missing values
I have been struggling with this issue for a bit and even though there are some workarounds i would assume, I would love to know if there is an elegant way to achieve this result:
import pandas as pd import numpy as np data = np.array([ [1,10], [2,12], [4,13], [5,14], [8,15]]) df1 = pd.DataFrame(data=data, index=range(0,5), columns=['x','a']) data = np.array([ [2,100,101], [3,120,122], [4,130,132], [7,140,142], [9,150,151], [12,160,152]]) df2 = pd.DataFrame(data=data, index=range(0,6), columns=['x','b','c'])
Now I would like to have a data frame that concatenate those 2 and fill the missing values with the previous value or the first value otherwise. Both data frames can have differnet sizes, what we are interested in here is the unique column x.
That would be my desired output frame df_result. x is the aggregated unique "x" between the 2 frames
x a b c 0 1 10 100 101 1 2 12 100 101 2 3 12 120 122 3 4 13 130 132 4 5 14 130 132 5 7 14 140 142 6 8 15 140 142 7 9 15 150 151 8 12 15 160 152
Any help or hint would be much appreciated, thank you very much

Keras concatenate LSTM model with nonLSTM model
I have two data. One is time series and the other contains features such as Sex, education, etc. and I want to concatenate output of LSTM model and a dense model. However, I got an error message (look at the end).
This is what the data looks like:
And this is the code:
# PAY_data net input1 = Input(shape=(6,1)) pay = LSTM(10)(input1) pay = Dense(10, activation='relu')(pay) # DEMO_data net input2 = Input(shape=(5,1)) demo = Dense(10, activation='relu')(input2) demo = Dense(10, activation='relu')(demo) merge = concatenate([pay, demo]) hidden1 = Dense(10, activation='relu')(merge) output = Dense(1, activation='sigmoid')(merge) model = Model(inputs=[input1, input2], outputs=output) print(model.summary()) model.compile(loss='binary_crossentropy', optimizer='adam', metrics= ['accuracy']) model.fit([PAY_data, DEMO_data], y,nb_epoch=20, batch_size=50, verbose=2, validation_split=0.2)
and this is the error I get: