creating a correct mathematical expression from matlab code?
I have a labeled image L and binary image B. I am able to identify the necessary labels which have 1 in the binary image.
Explanation: We will take each and every label from 1 to 6. say, L=1 at (row,column)(1,1),we will check the same at binary image B(row,column) i.e.,B(1,1)=1. we will increase the count ctr_W by 1. For label L=1 the count ctr_w=13,count ctr_B=2; so count ctr_W>count ctr_B. we will take L=1 as white. For label L=2 ctr_w=1 and ctr_B=14;so ctr_w
L={1 1 1 1 1 2 2 2 2 2
1 1 1 1 1 2 2 2 2 2
1 1 1 1 1 2 2 2 2 2
3 3 3 4 4 5 5 5 6 6
3 3 3 4 4 5 5 5 6 6}
B={ 1 1 1 1 1 0 0 0 0 1
1 0 0 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 1 0}
labels={1,2,3,4,5,6}
while ~isempty(labels)
for i=length(lebels)
Hih=labels(i);
[r,c] =find(L==Hih);
ctr_B= 0;
ctr_W=0;
for i = 1 : length(r)
if((B(r(i),c(i)) ~= 0))
ctr_W=ctr_W+1;
else
ctr_B=ctr_B+1;
end
end
if(ctr_W>ctr_B)
white=[white,Hih];
else
black=[black,Hih];
end
end
end
I got labels 1,6. How can I write the mathematical expression which exactly represents the code? kindly help me. Thanks in advance
1 answer

If I understand correctly you want to count labels, only if they are "enabled" by the binary mask.
First of all: learn the difference between cell arrays and matrices, and realize why you do not need cell arrays.
L=[1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 3 3 3 4 4 5 5 5 6 6 3 3 3 4 4 5 5 5 6 6]; B=[1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0];
Mask the labels:
L2=L.*B;
Count how many of each unique value exist:
counts=histcounts(L2);
Ignore the first one (zeroes)
counts(1)=[];
There you go,
counts
contains how many of each of the labels exist, within the mask.
See also questions close to this topic

Undefined variable "daq" or class "daq.ni.ThermocoupleType.setValue"
This is probably a silly question, but I haven't found a good answer anywhere on the internet yet.
I am trying to acquire temperature data from an NI TC01 thermocouple, but everytime I run the sample code  link: https://www.mathworks.com/matlabcentral/fileexchange/29707readanationalinstrumentsusbtc01singlechannelthermometerinmatlab
I get the error [Undefined variable "daq" or class "daq.ni.ThermocoupleType.setValue"].
I know that I have the data acquisition toolbox, but I can't figure out how to run this code. Does anyone have any ideas/solutions?
Thank you

How object recognition name converted into voice in Matlab?
Hi i am trying to convert name of object in voice .Name of object which come after object recognition.How this be possible enter image description here

Creating an N input, 5 output feedforward neural network in MATLAB
I need to create a feedforward neural network in MATLAB that is capable of receiving either 3x59 or 1x177 inputs and classifying the input data using 1 of 6 output neurons.
To be more specific, the input to the neural network is data extracted from facial images, whilst the outputs are 5 emotions that classify the emotion displayed by the person in the image. I'd like the network to be able to somewhat accurately classify the emotion displayed in each image using the inputs and by taking the neuron with the largest output as its prediction.
Collecting the inputs has already been programmed, and I am now in a position where I have the 3x59 matrix or the 1x177 matrix ready to be input into a network, I also have the desired outputs for each image held in an array object within matlab, but in string form.
I'm not sure how I'd go about doing this in MATLAB, I was looking at this page on creating and training a feedforward NN, but I'm not sure if this is what I need. This page also doesn't make it clear how to structure my desired outputs so that I can successfully train the network.
Also, I'm confused about structuring the desired output for to train the neural network with. I have a text file that contains the actual emotion displayed in each image, but this is displayed in string form and needs to be converted into some kind of mathematical representation. Obviously for each image there is one correct emotion and four incorrect emotions. Does this mean I should convert the desired emotions into some kind of matrix that contains the emotions, with the correct emotion for each image being a 1, whilst the incorrect emotions are a 0? Can I then use this to train the network with?

OpenCV predict() vs detectMultiScale()
I'm working on doing some Face, Gender, and Age detection using OpenCV. I have a bunch of images I use to train the models, Essentally I currently have the following:
Ptr<cv::face::FaceRecognizer> model = cv::face::LBPHFaceRecognizer::create(9, 9); std::vector<int> labels; std::vector<std::string> imageFileNames; for (int currImageIndex = 0; currImageIndex < imageFileNames.size(); currImageIndex++) { cv::Mat currMatrix; std::string currentFileName = imageFileNames[currImageIndex]; std::string gender; int currID = 1; //Save the image and the corresponding ID to the list(s). currMatrix = imread(currentFileName , CV_LOAD_IMAGE_GRAYSCALE); if (currMatrix.data != NULL) { images.push_back(currMatrix); labels.push_back(currID); } } model>train(images, labels); model>write("C:\\temp.xml");
Then using the
temp.xml
heuristic, I predict the geneder like so:gendermodel>predict(currMat, predictedLabel, conf);
However, I came across this implementation using
detectMultiScale()
and a"Cascade Classifier"
. What is the diffrence? Is there a performance advantage to using aCascade Classifier
vs the way I am currently doing it? DoesdetectMultiScale()
work better thenpredict()
? 
How to get image height and width using CarrierWave?
I'm new to Rails. I try to create an app for working with images. It should do some actions depending on image size.
I use
CarrierWave
as uploader and after uploading I need to get the imagewidth
andheight
and save it in a variable. How can I do that? 
The truth value of an array with more than one element is ambiguous Python error
I need to detect if image is pizelized or not. So i use a python code, that was taken from other stackoverflow post:
import numpy as np from PIL import Image, ImageChops im = Image.open('img/low2.jpg') im2 = im.transform(im.size, Image.AFFINE, (1,0,1,0,1,1)) im3 = ImageChops.subtract(im, im2) im3 = np.asarray(im3) im3 = np.sum(im3,axis=0)[:1] mean = np.mean(im3) peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2]) mean_spacing = np.mean(peak_spacing) std_spacing = np.std(peak_spacing)
I'm getting this error:
File "pixelated.py", line 11, in peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
How can i fix this? I'm newbie in Python, please give me any idea or help.

Mixing expression, plain text and newline in ggplot2 expression
I am trying to create some labels/stickers using
ggplot2
. I am pulling the text for the labels from a source and tyring to plot. I am able to do that as follows:labtxt1 < c("This text should be bold", "This text should also be bold", "Another text to be bold") labtxt1 < strwrap(labtxt1, width = 20) labtxt2 < c("This text should not be bold", "This text should also not be bold", "Another text to be plain") labtxt2 < strwrap(labtxt2, width = 20) library(ggplot2) library(Hmisc) labtxt < c(labtxt1, labtxt2) labtxt < paste(labtxt, collapse = "\n", sep = "") labtxt < escapeRegex(labtxt) ggplot(x=1, y = 1) + annotate("text", x = 0.5, y = 0.5, label = labtxt, colour = "red", parse = F, lineheight = 0.8)
How to now make the text in
labtxt1
to bold, along with the text inlabtxt2
as plain maintaining the justification andlinewidth
?I have tried with
expression
with\n
, which messes up the justification, and withatop
, but which messes up the linewidth.If I try to annotate separately, then positioning is difficult as the lenght of
labtxt1
andlabtxt2
varies in for different labels/stickers.How to get the desired result?

mathematica bincount function alterations code
I am in need of a little help in the post processing part of the tonatiuh software's output binary file(the output is in form of The photon id. The xcoordinate of the photon. The ycoordinate of the photon. The zcoordinate of the photon. The side of the surface in which the photon is impinging (0 if is in the back side, and 1 if is in the front side))the post processing is done in mathematica and for my project I need to make a little alterations to the program given in the example code ' https://github.com/iatcener/tonatiuh/wiki/TutorialParabolicDishV201 '. In the example code a flat disk was assumed as a receiver though for my project purpose I need a vertical cylindrical receiver in which the graph of flux density is to be plotted for it's outer surface (an example of expected output plot is in attachments1).

adding trigonometrical functions in parsing calculator using java and The Shuntingyard algorithm
Firstly i would like to thank you for reading my post . i have been looking on implementing a parsing calculator . so far i was able to make it with basic operations (+ ,  , / , *). for that i used The Shuntingyard algorithm (The shuntingyard algorithm is a method for parsing mathematical expressions written in infix notation to Reverse Polish Notation (RPN).) now the code works perfectly but i want to add trigonometrical expressions like (cos tan sin and log ). can you help me please ?
actually i'm a swift and c# developer but i'm obliged to work on java on this one . so here is the code that is working without the implementation of sin cos etc...
package expressionparser; import java.util.*; public class ExpressionParser { // Associativity constants for operators private static final int LEFT_ASSOC = 0; private static final int RIGHT_ASSOC = 1; // Operators private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>(); static { // Map<"token", []{precendence, associativity}> OPERATORS.put("+", new int[] { 0, LEFT_ASSOC }); OPERATORS.put("", new int[] { 0, LEFT_ASSOC }); OPERATORS.put("*", new int[] { 5, LEFT_ASSOC }); OPERATORS.put("/", new int[] { 5, LEFT_ASSOC }); } // Test if token is an operator private static boolean isOperator(String token) { return OPERATORS.containsKey(token); } // Test associativity of operator token private static boolean isAssociative(String token, int type) { if (!isOperator(token)) { throw new IllegalArgumentException("Invalid token: " + token); } if (OPERATORS.get(token)[1] == type) { return true; } return false; } // Compare precedence of operators. private static final int cmpPrecedence(String token1, String token2) { if (!isOperator(token1)  !isOperator(token2)) { throw new IllegalArgumentException("Invalid tokens: " + token1 + " " + token2); } return OPERATORS.get(token1)[0]  OPERATORS.get(token2)[0]; } // Convert infix expression format into reverse Polish notation public static String[] infixToRPN(String[] inputTokens) { ArrayList<String> out = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); // For each token for (String token : inputTokens) { // If token is an operator if (isOperator(token)) { // While stack not empty AND stack top element // is an operator while (!stack.empty() && isOperator(stack.peek())) { if ((isAssociative(token, LEFT_ASSOC) && cmpPrecedence(token, stack.peek()) <= 0)  (isAssociative(token, RIGHT_ASSOC) && cmpPrecedence(token, stack.peek()) < 0)) { out.add(stack.pop()); continue; } break; } // Push the new operator on the stack stack.push(token); } // If token is a left bracket '(' else if (token.equals("(")) { stack.push(token); // } // If token is a right bracket ')' else if (token.equals(")")) { while (!stack.empty() && !stack.peek().equals("(")) { out.add(stack.pop()); } stack.pop(); } // If token is a number else { out.add(token); } } while (!stack.empty()) { out.add(stack.pop()); } String[] output = new String[out.size()]; return out.toArray(output); } public static double RPNtoDouble(String[] tokens) { Stack<String> stack = new Stack<String>(); // For each token for (String token : tokens) { // If the token is a value push it onto the stack if (!isOperator(token)) { stack.push(token); } else { // Token is an operator: pop top two entries Double d2 = Double.valueOf( stack.pop() ); Double d1 = Double.valueOf( stack.pop() ); //Get the result Double result = token.compareTo("+") == 0 ? d1 + d2 : token.compareTo("") == 0 ? d1  d2 : token.compareTo("*") == 0 ? d1 * d2 : d1 / d2; // Push result onto stack stack.push( String.valueOf( result )); } } return Double.valueOf(stack.pop()); } public static void main(String[] args) { String[] input = "( 1 + 2 ) * ( 3 / 4 )  ( 5 + 6 )".split(" "); String[] output = infixToRPN(input); // Build output RPN string minus the commas for (String token : output) { System.out.print(token + " "); } // Feed the RPN string to RPNtoDouble to give result Double result = RPNtoDouble( output ); System.out.print(result); }

Binary Erode Speedup with Cython
I am looking to accelerate a binary erosion image processing function with Cython, although I am new to Cython. I am not seeing the drastic speedups I was expecting. I am looking for help to optimize this code as I am still not familiar with how C types, indexing, memory views, and objects can be utilized to enhance performance. Below is the source code and output of the Cython function, python function using SciPy module, setup.py, and jupyter notebook.
Cython code erode.pyx
import numpy as np cimport numpy as np DTYPE = np.int_ ctypedef np.int_t DTYPE_t def erode(long [:,:] img): # Variables cdef int height, width, local_min cdef int vals[5] height = img.shape[0] width = img.shape[1] # Padded Array cdef np.ndarray[DTYPE_t, ndim=2] padded = np.zeros((height+2, width+2), dtype = DTYPE) padded[1:height+1,1:width+1] = img #Return array cdef np.ndarray[DTYPE_t, ndim=2] eroded = np.zeros((height,width),dtype=DTYPE) cdef int i,j for i in range(height): for j in range(width): vals = [padded[i+1,j+1], padded[i,j+1], padded[i+1,j],padded[i+1,j+2],padded[i+2,j+1]] local_min = min(vals) eroded[i,j] = local_min return eroded
Python code erode_py.py
import numpy as np from scipy.ndimage import binary_erosion def erode_py(img): strel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8) img = img.astype(np.uint8) eroded_image = binary_erosion(img, strel, border_value=0) return eroded_image
setup.py
from distutils.core import setup from Cython.Build import cythonize import numpy setup( name='binary_erode_build', ext_modules=cythonize("erode.pyx"), include_dirs=[numpy.get_include()] )
Jupyter notebook
import numpy as np import erode import erode_py obj = np.array([[0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0]], dtype=np.int_) %timeit n100 r100 erode.erode(obj) %timeit n100 r100 erode_py.erode_py(obj) 42.8 µs ± 10.3 µs per loop (mean ± std. dev. of 100 runs, 100 loops each) 44.2 µs ± 14.4 µs per loop (mean ± std. dev. of 100 runs, 100 loops each)

Binarize a Gray Scale QR Code image while maintaining its readibility
We get computer generated QR Codes which are in Gray Scale format. These QR Codes are readable. However, we need to convert these Grayscale QR Codes into a Binary Format for a particular end application. This is where the problem arises. When we binarize the QR Code, we lose it's readibility (primarily reading via CamScanner app). We have tried some basic Binarization techniques available in OpenCV like simple Binarization at a fixed global threshold (tried multiple threshold values like 60, 80, 127, 150, 190) and adaptive threshold with weighted average. None of them is giving desired readbility results.

Binary image reconstruction Algorithm in Ruby
I am facing a problem where i need reconstruct a binary image of matrix MXN
Problem:
Binary tomography deals with the problem of reconstructing binary images from a small number of projections. One of its most basic problems is to construct a binary ({0,1}valued) matrix with given row and column sums. This is not always possible and your task is to determine when it is.
Input The first line of input contains two numbers 1≤m,n≤1000, the number of rows and columns of the matrix. The next line contains m numbers 0≤ri≤n – the sum of each row in the matrix. The third line contains n numbers 0≤cj≤m – the sum of each column in the matrix.
Output Output “Yes” if there exists an mbyn matrix A, with each element either beeing 0 or 1, such that
∑j=1nAi,j=ri∀i∈{1,2,…,m} and ∑i=1mAi,j=cj∀j∈{1,2,…,n}. Otherwise output “No”.
Above image tells that gray grids: 1 and White Grids: 0
Please help me to deduce.