Is there a way to use a bitmap or glide rather than a drawable image in MPAndroidChart? - mpandroidchart

int[] moodIconRes = {
R.drawable.ic_emoticon_01, R.drawable.ic_emoticon_02, R.drawable.ic_emoticon_03,
R.drawable.ic_emoticon_04, R.drawable.ic_emoticon_05, R.drawable.ic_emoticon_06,
R.drawable.ic_emoticon_07, R.drawable.ic_emoticon_08, R.drawable.ic_emoticon_09,
R.drawable.ic_emoticon_10, R.drawable.ic_emoticon_11, R.drawable.ic_emoticon_12
};
Right now I am using it as a drawable.
private void setData1(HashMap<Integer, Integer> hashMap) {
ArrayList entries = new ArrayList<>();
int totalCount = 0; // 총 기분 수 (전체, 올해, 이번달마다 달라지는 값이므로 호출마다 초기화)
maxMoodIndex = -1; // 제일 많은 기분 종류
maxCount = -1; // 제일 많은 기분의 개수
colors.clear(); // 파이차트를 구성할 색깔배열 clear (전체, 올해, 이번달마다 달라지는 값이므로 clear 필요)
for(int i = 0; i < 12; i++) {
int count = 0;
if(hashMap.containsKey(i)) {
count = hashMap.get(i);
setMoodCount(i, count);
totalCount += count;
addColor(i); // 기분 종류에 맞게 색깔 설정
entries.add(new PieEntry(
count,
"",
ContextCompat.getDrawable(requireContext(), moodIconRes[i])
));
} else {
setMoodCount(i, count); // 개수 0
}
}
I wonder if there is a way to call it in the form of a bitmap or r.id.imageview rather than a drawable image in this part. I'd appreciate it if someone could give me an idea.

You can use BitmapDrawable
Drawable d = new BitmapDrawable(getResources(), bitmap);

Related

Slow image processing of images from filesystem as compared to the webcam

I was able to follow the csharp-sample-apps from the github repo for Affectiva. I ran the demo using my webcam and the processing and performance was great.I am not getting the same processing speed from the PhotoDetector when I try to run it over images in filesystem. Any help or improvement would be appreciated.
namespace Logical.EmocaoFace
{
public class AnaliseEmocao : Affdex.ImageListener, Affdex.ProcessStatusListener
{
private Bitmap img { get; set; }
private Dictionary<int, Affdex.Face> faces { get; set; }
private Affdex.Detector detector { get; set; }
private ReaderWriterLock rwLock { get; set; }
public void processaEmocaoImagem()
{
for (int i = 0; i < resultado.count; i++){
RetornaEmocaoFace();
if (faceAffdex != null)
{
}
}
}
public void RetornaEmocaoFace(string caminhoImagem)
{
Affdex.Detector detector = new Affdex.PhotoDetector(1, Affdex.FaceDetectorMode.LARGE_FACES);
detector.setImageListener(this);
detector.setProcessStatusListener(this);
if (detector != null)
{
//ProcessVideo videoForm = new ProcessVideo(detector);
detector.setClassifierPath(#"D:\Desenvolvimento\Componentes\Afectiva\data");
detector.setDetectAllEmotions(true);
detector.setDetectAllExpressions(false);
detector.setDetectAllEmojis(false);
detector.setDetectAllAppearances(false);
detector.start();
((Affdex.PhotoDetector)detector).process(LoadFrameFromFile(caminhoImagem));
detector.stop();
}
}
static Affdex.Frame LoadFrameFromFile(string fileName)
{
Bitmap bitmap = new Bitmap(fileName);
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int numBytes = bitmap.Width * bitmap.Height * 3;
byte[] rgbValues = new byte[numBytes];
int data_x = 0;
int ptr_x = 0;
int row_bytes = bitmap.Width * 3;
// The bitmap requires bitmap data to be byte aligned.
// http://stackoverflow.com/questions/20743134/converting-opencv-image-to-gdi-bitmap-doesnt-work-depends-on-image-size
for (int y = 0; y < bitmap.Height; y++)
{
Marshal.Copy(ptr + ptr_x, rgbValues, data_x, row_bytes);//(pixels, data_x, ptr + ptr_x, row_bytes);
data_x += row_bytes;
ptr_x += bmpData.Stride;
}
bitmap.UnlockBits(bmpData);
//Affdex.Frame retorno = new Affdex.Frame(bitmap.Width, bitmap.Height, rgbValues, Affdex.Frame.COLOR_FORMAT.BGR);
//bitmap.Dispose();
//return retorno;
return new Affdex.Frame(bitmap.Width, bitmap.Height, rgbValues, Affdex.Frame.COLOR_FORMAT.BGR);
}
public void onImageCapture(Affdex.Frame frame)
{
frame.Dispose();
}
public void onImageResults(Dictionary<int, Affdex.Face> faces, Affdex.Frame frame)
{
byte[] pixels = frame.getBGRByteArray();
this.img = new Bitmap(frame.getWidth(), frame.getHeight(), PixelFormat.Format24bppRgb);
var bounds = new Rectangle(0, 0, frame.getWidth(), frame.getHeight());
BitmapData bmpData = img.LockBits(bounds, ImageLockMode.WriteOnly, img.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int data_x = 0;
int ptr_x = 0;
int row_bytes = frame.getWidth() * 3;
// The bitmap requires bitmap data to be byte aligned.
// http://stackoverflow.com/questions/20743134/converting-opencv-image-to-gdi-bitmap-doesnt-work-depends-on-image-size
for (int y = 0; y < frame.getHeight(); y++)
{
Marshal.Copy(pixels, data_x, ptr + ptr_x, row_bytes);
data_x += row_bytes;
ptr_x += bmpData.Stride;
}
img.UnlockBits(bmpData);
this.faces = faces;
frame.Dispose();
}
public void onProcessingException(Affdex.AffdexException A_0)
{
throw new NotImplementedException("Encountered an exception while processing " + A_0.ToString());
}
public void onProcessingFinished()
{
string idArquivo = CodEspaco + "," + System.Guid.NewGuid().ToString();
for(int i = 0; i < faces.Count; i++)
{
}
}
}
public static class GraphicsExtensions
{
public static void DrawCircle(this Graphics g, Pen pen,
float centerX, float centerY, float radius)
{
g.DrawEllipse(pen, centerX - radius, centerY - radius,
radius + radius, radius + radius);
}
}
}
Found the answer to my own question:
Using PhotoDetector is not ideal in this case since it is expensive to use the Face Detector configuration on subsequent frame calls.
The best option to improve the performance would be to use an instance of the FrameDetector Class.
Here is a getting started guide to analyze-frames.

Color change a background in processing w/ out affecting particles

I'm trying to fade a background in and out into different colors. I decided to try drawing a rect rather than using background, but I'm getting trails on my particles, because the background isn't getting drawn. Suggestions on how to fix this?
// main tab
ArrayList<ParticleSystem> systems;
PVector windRight = new PVector(0.1,0);
PVector sortaSpeed = new PVector(-0.1,0);
PVector gravity = new PVector(0,0.05);
boolean wR = false;
boolean sP = false;
boolean cS = false;
int limit = 8;
int alpha = 10;
color[] colorArray = {color(0,0,0,alpha),color(16, 37, 43,alpha),color(51, 10, 10,alpha),color(126, 255, 0,alpha)};
int currentColor;
int nextColor;
boolean change = false;
void setup() {
size(640,480);
systems = new ArrayList<ParticleSystem>();
smooth();
noStroke();
currentColor = 0;
for(int i = 0; i < limit; i++){
systems.add(new ParticleSystem(random(100,200),10,new PVector(random(100,500),-5))); //random(480)
}
background(0);
}
void draw() {
//rect(0, 0, 2000, 2000);
fill(colorArray[currentColor]);
rect(0, 0, width*2, height*2);
//background(colorArray[currentColor]);
if(change){
currentColor = nextColor;
change = false;
}
if(!systems.isEmpty()){
for (int i =0; i < systems.size(); i++){
ParticleSystem ps = systems.get(i);
ps.applyForce(gravity);
ps.run();
if(wR){
ps.applyForce(windRight);
}
if(sP){
ps.applyForce(sortaSpeed);
}
}
}
}
void keyPressed() {
if(key == 'w'){
wR = true;
print("w");
}
if(key == 'a'){
print('a');
sP = true;
}
}
void keyReleased(){
if(key == 'w'){
wR = false;
} else if(key == 'a'){
sP = false;
} else if(key == 's'){
if(key == 's'){
change = true;
println("currentColor: "+currentColor);
int newColor = currentColor;
while (newColor == currentColor)
newColor=(int) random(colorArray.length);
nextColor = newColor;
}
} // end of cS
}
In the future, please try to post an MCVE. Right now we can't run your code because it contains compiler errors. We don't need to see your entire sketch anyway though, just a small example that gets the point across.
But your problem is caused because you're trying to use alpha values in your background. That won't work with the background() function because that function ignores alpha values, and it won't work with the rect() function because then you won't be clearing out old frames- you'll see them through the transparent rectangle.
Instead, you could use the lerpColor() function to calculate the transition from one color to another over time.
Here's an example that transitions between random colors:
color fromColor = getRandomColor();
color toColor = getRandomColor();
float currentLerpValue = 0;
float lerpStep = .01;
void draw() {
color currentColor = lerpColor(fromColor, toColor, currentLerpValue);
currentLerpValue += lerpStep;
if (currentLerpValue >= 1) {
fromColor = currentColor;
toColor= getRandomColor();
currentLerpValue = 0;
}
background(currentColor);
}
color getRandomColor() {
return color(random(255), random(255), random(255));
}

ArrayList Method Returns a null ArrayList, main program cannot access

I'm trying to create a basic function that calls on a method that creates the 2D ArrayList that will be used further in the main program to do things like calculate the row and column sums as well as print out the triangle.
However, after it runs the ArrayList returns null. What's going on?
Thanks,
public class Trib
{
private ArrayList<ArrayList<Integer>> triangle;
private int Asize;
public Trib (int size)
{
// convert the argument to type 'int' to be used in the program
Asize = size;
// create an ArrayList of ArrayLists, it will have 'size' number ArrayLists contained within
ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>(size);
// create the inner ArrayLists
for (int i = 0; i < size; i++)
{
// add to index 'i' of our ArrayList a new ArrayList of size (i+1)
triangle.add(new ArrayList<Integer>(i+1));
for (int j = 0; j <= i; j++)
{
if (j==0 || j == i)
{
triangle.get(i).add(1);
}
else
triangle.get(i).add(triangle.get(i-1).get(j-1)+triangle.get(i-1).get(j));
System.out.print(triangle.get(i).get(j) + " ");
}
System.out.println();
}
triangle.clone();
}
public void printTriangle()
{
System.out.print(triangle.get(1).get(1));
/*for (int i = 0; i < Asize; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print(triangle.get(1).get(1) + " ");
}
System.out.println();
}*/
}
/*public Trib()
{
this(5);
}*/
/*public int Psize()
{
return triangle.size();
}
public ArrayList<Integer> sumRows()
{
ArrayList<Integer> row_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
row_sum.add(triangle.get(i).get(j));
}
}
return row_sum;
}
public ArrayList<Integer> sumCols()
{
ArrayList<Integer> col_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
col_sum.add(triangle.get(i).get(i));
}
}
return col_sum;
}*/
public static void main(String[] args)
{
if(args.length < 1)
{
System.err.println("Sorry, this program needs an integer argument.");
System.exit(1);
}
Trib pt = new Trib(Integer.parseInt(args[0]));
pt.printTriangle();
//ArrayList<Object> sum_rows = new ArrayList<Object>(pt.Psize());
// sum_rows.add;
System.out.println("\nHere are the sum of rows:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.println(sum_rows.get(i));
//ArrayList<Integer> sum_cols = new ArrayList<Integer>(pt.Psize());
System.out.println("\nHere are the sum of columns:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.printf("%-5d", sum_cols.get(i));
}
}
Watch out what's what you are doing: Notice that you have TWO variables named "triangle": The first one is an instance variable and the second is a local variable, which is the only one you have initialized.
My suggestion to avoid this common mistake is to pre-pend "this." to any use of what you intend must be an instance variable. And, if in doubt, if you use a development environment as Eclipse, press CTRL and click on your variable to navigate to the point where it is declared.

Why can't I get input from the ifstream?

I am trying to read in a text file for a maze program. The input is something like:
10 10
OO+E+OO+++
O++O+O+OOO
OOOOOO+O+O
+++++O++OO
OOO+OOO+O+
O+O+O+++O+
O+O+OOO+OO
++O+++O++O
O+OOOOO++O
O+O++O+OOO
When the user click on the open button, this opens a open file dialog box
{
openFileDialog1->InitialDirectory = "C:\Desktop;";
openFileDialog1->Filter = "Maze files (*.DAT)|*.DAT";
if (openFileDialog1->ShowDialog() == ::DialogResult::OK)
{
char filename[1024];
for (int i = 0; i < openFileDialog1->FileName->Length; i++)
{
filename[i] = openFileDialog1->FileName[i];
}
ifstream ifs;
ifs.open(filename); // NULL terminate this
maze = new Maze( panel1, ifs);
ifs.close();
}
}
the following is the maze constructor
Maze::Maze( Panel ^ drawingPanel, ifstream & ifs )
{
try
{
valid = false;
ifs >> width >> height;
int temp = width;
drawingPanel->Size.Width = width;
drawingPanel->Size.Height = height;
for (int i = 0; i < height; i++) // height is always nothing
for (int j = 0; j < width; j++)
{
if (orig[j][i] == DEADEND ||
orig[j][i] == OPEN ||
orig[j][i] == EXIT )
ifs >> orig[j][i]; // NULLS????
else
throw 'D'; // i had to throw something....so i threw the D /* make a slit class and throw the D there? slit.fill(D); */
}
// this should be last
panel = drawingPanel;
valid = true;
}
catch (...)
{
valid = false;
MessageBox::Show( "Not a proper maze file!" );
}
}
when the program runs: ifs >> width >> height width and height do not get set correctly.
I have searched this site for this problem and have not been able to find anything that has helped. Sorry for my inexperience, any help is greatly appreciated.
You'e program very ugly : don't know if you're programming in C or C++ or C++/CLI, or try to mix the 3...
Because you use Windows Form projet, i will give you a .Net solution for read a file, it's not the better solution but this does not mix things.
First for read the file, on a first window :
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter = "Maze Files (*.dat) | *.dat";
if (openFileDialog1->ShowDialog() == ::DialogResult::OK)
{
String ^fileName = openFileDialog1->FileName;
IO::StreamReader ^myMazeFile = gcnew IO::StreamReader(fileName);
String ^content = myMazeFile->ReadToEnd();
richTextBox1->Text = content;
myMazeFile->Close();
// display button for open second form wich draw maze
button2->Visible = true;
}
}
now we have our file content, so we pass it to a second form who will draw the maze :
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
String ^content = richTextBox1->Text;
Maze ^frm = gcnew Maze(content);
frm->Show();
}
Second window, create overload constructor :
Maze(String ^contentMap)
{
InitializeComponent();
String ^dimension = getWords(contentMap, 2);
array<String ^> ^coordsString = dimension->Split(gcnew array<Char> {' '});
m_width = Convert::ToInt32(coordsString[0]);
m_height = Convert::ToInt32(coordsString[1]);
panel1->Width = m_width;
panel1->Height = m_height;
}
getWords method :
String ^getWords(String ^input, int numWords)
{
try
{
int words = numWords;
for (int i = 0; i < input->Length; ++i)
{
if (input[i] == ' ' ||input[i] == '\n')
words--;
if (words == 0)
{
return input->Substring(0, i);
}
}
}
catch (Exception ^ex)
{
// ...
}
return String::Empty;
}
You have your dimension in full .Net (private member m_width and m_height).

Detect collisions between objects in arrays

So I need to detect the collision of multiple objects that are stored in two different arrays or arrayLists. I have confirmed that the collision detection method itself is functioning properly. The problem is that the objects colliding are supposed to disappear and be removed from the array, and I'm not sure how to go about this.
public class GamePanel extends PApplet{
private boolean myRunningStatus;
private final int HEIGHT = 700;
private final int WIDTH = 1200;
private final int SHOT_SPEED = -20;
private int numStars = 0, numEnemies = 0;
private Hero hero;
private Enemy[] enemies;
private List <Star> stars;
public GamePanel(){
myRunningStatus = true;
createEnemies();
createStars();
createHero();
updateEnemies();
}
public void createEnemies(){
enemies = new Enemy[10];
for (int i=0; i<enemies.length; i++){
enemies[i] = new Enemy(random(1, WIDTH), random(1, HEIGHT), 5, 20);
}
}
public void createHero(){
hero = new Hero(mouseX, mouseY);
}
public void createStars(){
stars = new ArrayList <Star>();
}
public Star generateStar(){
Star star = new Star(hero.getHeroX(), hero.getHeroY());
return star;
}
public void setup(){
background(255);
size(WIDTH, HEIGHT);
hero.render(this);
}
public void draw(){
if(myRunningStatus){
background(255);
hero.render(this);
for(int i=0; i<enemies.length; i++){
enemies[i].render(this);
enemies[i].move();
}
for(int i=0; i<stars.size(); i++){
if(stars.get(i) != null){
stars.get(i).render(this);
stars.get(i).move(SHOT_SPEED);
if(stars.get(i).getYPos() < 0){
stars.remove(i);
}
}
}
}
}
//this is the method I'm using to find the collisions between the objects and remove them
public void updateEnemies(){
for(int i=0; i<enemies.length; i++){
for(int j=0; j<stars.size(); j++){
if(enemies[i].starHit(stars.get(j))){
stars.set(j, null);
enemies[i] = null;
}
}
}
}
public void mouseMoved(){
if(myRunningStatus){
hero.setHeroX(mouseX);
hero.setHeroY(mouseY);
}
}
public void mouseClicked(){
for (int i=0; i<10;){
stars.add(i, generateStar());
break;
}
}
Instead of setting things equal to null, it would be better to remove them outright from the list. I would use an ArrayList for both enemies and stars, then call list.remove(i) during collision detection. Don't forget that this will change the size of the list, so you'll have to do i-- every time you remove an element to compensate.
Also, this confused me. You set elements of enemies equal to null:
if(enemies[i].starHit(stars.get(j))){
stars.set(j, null);
enemies[i] = null;
}
But don't check for it here, so shouldn't you be getting NPEs?
for(int i=0; i<enemies.length; i++){
enemies[i].render(this);
enemies[i].move();
}