2026년 8월 20일 목요일

Claude Code vs Codex vs Gemini vs Grok: Which AI Assistant for Which Task

 The list of AI assistants worth knowing has gotten long. A while back, using ChatGPT well was enough to feel ahead of the curve. Now there's Claude, Claude Code, Codex, Gemini, and Grok, and the names and feature sets blur together fast. I use these for technical and engineering work — process data, analysis scripts, reading papers and reports, staying current on fast-moving tech — so I ran the same kind of tasks through all four and compared where each one actually earns its keep. Note: this is about Claude Code, the coding-and-project agent, not the general chat version of Claude.

The short version

  • Claude Code — best at reading and explaining existing code
  • Codex — best at running project-scale coding work and automation
  • Gemini — best at digesting and comparing large volumes of documents at once
  • Grok — best at surfacing what's happening right now

None of them is universally "the best" — the task determines the right tool.

1. Claude Code — reads your codebase like a colleague who's actually paying attention

Claude Code doesn't work like pasting a snippet into a chat box. It looks across a project's files, figures out how they connect, and works from that picture. For a data-analysis project, you might ask:

First check this project's file structure. Explain what each file does, and trace how data flows in and gets turned into the output charts. Don't modify anything yet — just analyze.

That's genuinely useful on old code you wrote yourself and no longer fully remember — vague variable names, no comments, no memory of why a given approach was used. Claude Code is good at reconstructing that story.

Strengths: understanding existing code structure, planning before it touches anything, working across multiple files, explaining errors, summarizing what changed after an edit.
Weaknesses: sometimes needs execution/environment setup; without a clearly scoped task it can touch more than intended; correctness of any technical calculation still needs independent verification.

2. Codex — feels like handing off actual project work

Codex also writes and edits code, but it's better suited to handling several linked tasks as one project rather than one-off snippets:

Read this CSV, check for missing values and outliers, compute mean and standard deviation for each variable, save the results as a table and a chart, and document how to run it in a README. Show me your plan before you start.

OpenAI describes Codex as a coding agent for writing, reviewing, and shipping project-level work — feature development, fixes, and refactors in one pass. In technical/engineering work, that maps to: cleaning up result files, repetitive data transforms, auto-generating charts, comparing results across conditions, refactoring analysis scripts, small internal tools, and figure-generation pipelines. If you're re-running the same analysis on new data every week, this is where the time savings compound.

Strengths: handles project-scale work well, good for automating repeated tasks, chains writing/editing/running/reviewing together, easy to check step by step.
Weaknesses: needs a specific brief up front; handing it something too large at once makes results hard to verify; you still need to confirm the output actually serves your purpose.

Rough distinction: Claude Code is better for understanding code that already exists; Codex is better for pushing a multi-step task through to completion. Results vary by environment and model version, of course.

3. Gemini — the one for wading through a stack of documents

Gemini's advantage shows up once you're comparing several long documents, not just reading one. Google notes that Gemini's long-context capability can process large amounts of text, code, images, and video at once, with some models supporting over a million tokens of input. One report barely tests that; five related ones do:

Compare these 5 papers. Put the following into a table: 1. research goal 2. method 3. materials used 4. key results 5. limitations 6. where conclusions diverge 7. what still needs further study

Reports on similar topics differ in test conditions, samples, and measurement methods in ways that take a while to spot by hand; Gemini gets you a first-pass comparison table fast.

Strengths: comparing multiple documents, parsing long reports, producing tables/summaries, integrates with Drive/document workflows, can also pull in recent sources.
Weaknesses: feeding in more documents doesn't guarantee more accuracy; it can blend conditions from different sources; there's a real risk of reading only the summary and never the source. Always re-check numbers and conditions against the original after Gemini summarizes it — one sentence in a report can flip the conclusion.

4. Grok — fastest read on what's happening right now

Grok's edge is live search. According to xAI's documentation, Grok can pull current information via web and X search and browse pages while forming an answer. In fast-moving fields — AI, semiconductors, space, batteries — a few months is enough for information to go stale. A useful prompt:

Summarize the notable technical issues in the semiconductor industry over the last 3 months. Conditions: only use dated sources, separate company announcements from actual research results, include source links, and flag anything unverified separately.

It's genuinely good at surfacing recent articles and what people are actually saying online. Just remember: what gets talked about a lot and what's actually significant aren't the same thing. A result trending on social media isn't automatically validated.

Strengths: fast on recent developments, good read on industry/online sentiment, well suited to fast-moving fields, easy to follow up on search results.
Weaknesses: online buzz isn't technical evidence; attention-grabbing topics can look more important than they are; source reliability still needs checking yourself.

Same question, four tools

Ask "explain the difference between the G band and 2D band in graphene's Raman spectrum" to all four, and the value-add differs by what comes next:

  • Claude Code: good for building the analysis code or plotting the data
  • Codex: good for automating the pipeline that reads and processes the Raman data files
  • Gemini: good for comparing what several papers say about it
  • Grok: good for finding recent research or news on the topic

Same question, different follow-up work, different right tool.

A workflow that's worked for me

  1. Grok — quick scan for what's currently happening in the space
  2. Gemini — pull in papers/reports and map common ground and disagreement
  3. Claude Code — check how the existing analysis code works and where it can improve
  4. Codex — automate the repetitive processing and chart generation

Current awareness → gather sources → understand the code → automate the analysis.

Head-to-head summary

Claude CodeCodexGeminiGrok
Understanding codeExcellentGoodGoodFair
Editing codeExcellentExcellentGoodGood
Automating repeat tasksGoodExcellentGoodFair
Comparing long documentsGoodFairExcellentFair
Current-events searchFairFairGoodExcellent
Technical writingGoodFairGoodFair
Reading online sentimentFairFairGoodExcellent

Bottom line

Each one has a distinct personality once you use them enough: Claude Code feels like a colleague reading code alongside you; Codex like a developer you can actually hand a task to; Gemini like an assistant who's already read the stack of reports on your desk; Grok like the person who always knows what just happened. None of it should be taken at face value, though — especially for technical work, always check three things: is there a real source, is fact separated from speculation, and do the numbers and conditions actually hold up. These tools don't replace the thinking — they cut down the time spent reading, gathering, and organizing before you get to think.

AI features and models change constantly — check each service's current documentation before relying on it for real work. The Korean version of this post is on my Naver blog.

AI Video Tools Compared: Higgsfield vs Google AI Studio vs Grok (Seedance, Veo, Kling)

Once you decide to actually make AI video instead of just watching demos, the real question isn't "which model is best" — it's "which one is best for what I'm doing right now." I spent a few weeks running the same scenes through Seedance, Veo, Kling, and Grok Imagine, then compared the platforms — Higgsfield, Google AI Studio, and Grok — that give you access to them. Short version: Seedance and Kling win on raw output quality. Grok wins on cost-per-iteration, and iteration is most of what AI video actually is.

The models, one by one

Seedance — stunning output, terrifying to iterate on

Seedance is currently one of the most impressive video models around. Character motion is smooth, camera moves read as genuinely cinematic, and multi-image reference input holds up well. A prompt like:

A woman walks slowly through a night alley in Seoul. The camera follows her from behind, moving smoothly. Neon reflects off the wet asphalt, and car lights pass in the distance. Soft cinematic music and ambient city sound.

— comes back with mood and camera work genuinely well captured. The catch is price. AI video rarely nails a shot on the first try; you generate, discard, adjust, and regenerate. When each attempt costs real money, you stop experimenting and start playing it safe — which defeats the point. Seedance is best saved for final shots you've already validated elsewhere, not for exploring ideas.

Veo — realism and physics done right

Google's Veo is strong where things need to look real : natural motion, believable lighting and texture, and (on some models) integrated audio. It's a good fit for product ads, food and lifestyle scenes, natural human performance, and anything meant to look like it was actually filmed — think a coffee ad or a car commercial.

Accessed through Google AI Studio, Veo feels less like a video app and more like a lab bench: you pick the model, manage settings, and watch credits and API cost directly. That's great if you're building something programmatic, less great if you just want to make a nice video. Editing and story-management features are limited compared to a dedicated video platform.

Kling — consistency and shot control

Kling has been a strong image-to-video option for a while, and Kling 3.0 improved character/object consistency across multiple shots, plus native audio and multi-shot storyboarding. It shines when the same character needs to reappear across cuts:

The same character sits by a cafe window. Shot one: looking at her coffee cup. Shot two: slowly looking out the window. Shot three: camera moves to her side. Face and outfit stay identical across all three shots.

Kling handled that kind of continuity better than most alternatives. Downsides mirror Seedance: high-quality mode burns credits fast, generation isn't quick, and results vary enough between runs that repeated testing gets expensive.

Grok Imagine — not the best, but the easiest to iterate on

Grok Imagine won't out-render Seedance or Veo on any single metric. What it's good at is being cheap and fast enough that you actually generate ten variations instead of agonizing over one. It's well suited to turning a still image into motion, short-form clips, quick mood/motion tests, and generally throwaway experimentation. Faces and hands wobble more often than the premium models, and it's not built for long-form storytelling — but for the "try it, discard it, try again" loop, it's the most usable option by a wide margin.

Model comparison at a glance

Seedance Veo Kling Grok Imagine
Video quality Excellent Excellent Excellent Good
Character consistency Excellent Good Excellent Fair–Good
Physics/realism Good Excellent Good Fair
Camera work Excellent Good Excellent Good
Multi-shot support Good Fair–Good Excellent Fair
Native audio/lip-sync Yes Excellent Yes No
Generation speed Moderate Moderate Moderate Fast
Cost of iterating High High High Low

The platforms

Higgsfield — everything under one roof

Higgsfield's main pitch is access: Seedance, Veo, Kling, Sora, and Grok Imagine all live behind one subscription, alongside image generation, image-to-video, character consistency tools, start/end frame control, lip-sync, and ad-focused templates. Not juggling separate subscriptions to compare models is genuinely convenient, and it's a solid fit for anyone doing serious video or music-video production. The trade-off: the monthly cost adds up, credit draw varies by model, and "unlimited" tiers rarely mean every model is unlimited — run the good models a lot and credits disappear fast. It can feel like overkill if you're just experimenting casually.

Google AI Studio — a lab, not a studio

This is where you go to work with Veo (and other Google models) directly, with API access for automation. Great for developers and anyone building a product on top of these models; a bit much if your goal is simply "make one good video," since editing and scene-management tools are minimal and repeated testing racks up API cost you have to track yourself.

Grok — the lightest way to start

Not a professional editing platform, but a genuinely easy way to turn ideas and short clips into video fast, then throw away what doesn't work. Good for beginners, short-form/social content, and anyone who wants to test a lot without spending a lot. Not built for long-form storytelling or heavy editing — you'll want another tool for the final assembly.

Platform comparison

Platform Best for Strength Weakness
Higgsfield Serious video creators Multiple models + production tools in one place Subscription/credit cost adds up
Google AI Studio Developers, experimenters Direct Veo + API access Steep learning curve for non-developers
Grok Beginners, short-form creators Simple, cheap to iterate on Limited editing/production features

Recommended combos

  • Starting out: Grok alone — test ideas and short scenes without spending much.
  • Best quality/cost balance: Draft on Grok, then send only the shots you love to Seedance or Kling on Higgsfield.
  • Realistic ad footage: Veo through Google AI Studio.
  • Building automation or a product: Google AI Studio + the Veo API.

Bottom line

Seedance and Kling are genuinely impressive — and too expensive to use freely. Grok isn't always the best output, but it's the one you can actually afford to run ten times, and in AI video, picking the best two out of ten attempts usually beats betting everything on one expensive generation. My honest recommendation: don't start by subscribing to the priciest model. Test broadly on Grok first, then spend your premium credits only on the shots that already earned it.

Pricing, generation limits, and platform features for AI video tools change frequently — check each service's current terms before subscribing. The Korean version of this post is on my Naver blog .

How to Cut AI Video Generation Costs: Draft with Grok, Finish with Higgsfield

 If you have been playing with AI video generation, you already know the pattern. The free credits feel generous for about a week. Then you try to make something you actually care about, and the credits start melting.

I make AI music videos as a hobby (my day job is managing things in the semiconductor industry, which turns out to be cheaper). Along the way I burned through more credits than I would like to admit — extra arms, faces that change between shots, cameras that wander off in the wrong direction. This post is the cost-control pipeline I ended up with after all that: draft cheap, verify early, and spend real money only on shots you have already validated.

Why AI video burns money so fast

Video is just many images in a row, so every generation costs far more compute than a still image. On top of that, cost scales with almost every knob you can turn:

  • Longer clips
  • Higher resolution
  • Generating audio together with the video
  • Premium models (Veo, Kling, Seedance)
  • Character/object consistency features
  • Generating multiple scenes in one batch

And here is the painful part: you are charged even when the result is unusable. "Surely the next one will be fine" is the most expensive sentence in AI video production.

The core principle: never prototype on a premium model

Sedance and Kling produce great footage. But using them to explore ideas is like renting a film crew to scribble a storyboard. The pipeline that works:

Idea → reference image → motion test on a cheap model → final render on a premium model

Each stage filters out failures before they reach the expensive stage. Here is each step in detail.

Step 1 - Write the scene down before generating anything

The cheapest tool in this entire pipeline is a text file. "A woman walking through a city" will give you a vague, re-roll-inviting result. Pin the scene down first:

Purpose: lonely mood, protagonist walking at night
Character: woman in her 20s, black coat
Location: rain-soaked alley, Seoul
Camera: slow tracking shot following from behind
Motion: slow walk, hair moving in light wind
Mood: cold, melancholic, cinematic
Aspect ratio: 9:16 vertical

Every ambiguity you resolve on paper is a re-generation you do not pay for later.

Step 2 - Lock the reference image first

Do not go text-to-video directly. Generate a still image first and fix everything there: face, age, hairstyle, outfit, location, time of day, framing, lighting, aspect ratio.

An image you dislike costs one cheap re-roll. A video whose character is wearing the wrong coat costs the full video price — and you will notice it only after rendering. This single checkpoint improved my quality-per-credit more than anything else in the pipeline.

Step 3 - Test motion on Grok (or any budget tier)

This is the step that saved me the most money. Before touching a premium model, I run the shot through Grok's image-to-video. Any low-cost tier works the same way — Seedance mini at 480p, Kling's budget mode, whatever you have cheap access to.

A test prompt looks like this:

The woman in this image walks slowly forward. The camera follows her from behind. Her coat and hair move naturally in a light wind. City lights reflect on the wet pavement. Calm, cinematic mood. Slow camera movement.

You are not judging image quality here. You are checking five cheap-to-verify things:

  • Does the character move in the intended direction?
  • Is the camera movement natural?
  • Is the pacing right?
  • Do the character and background work together?
  • Does the mood match the music or story?

Step 4 - Send only the winners to a premium model

Once a shot passes the motion test, re-generate it properly. I use Higgsfield for this stage because it exposes Seedance, Veo, and Kling in one place, so the same image + prompt can be compared across models. My rough routing:

NeedModel
Character motionKling
Cinematic camera workSeedance
Realistic scenes + audioVeo
Fast, cheap idea testsGrok

Not every shot needs the top model. Routing by need means only a fraction of your footage is rendered at premium prices.

(Examples of Grok only video : https://youtube.com/shorts/92xqMIJYx3s?feature=share )

Step 5 - Generate short clips, not long ones

One 15-second generation fails more often, and more expensively, than four 4–6-second clips. Break the scene into cuts — "she stands at the alley entrance", "she walks in", "camera tracks her profile", "she stops and looks up" — then join them in your editor. Shorter clips fail cheaper and re-roll faster. (Some people report that Seedance handles action sequences better as one longer clip, so treat this as a default, not a law.)

Step 6 - Add audio in post, not in the model

Built-in audio generation is convenient and quietly expensive, because every re-roll regenerates the audio too. For music videos and short-form content, drop music and SFX in during editing instead. During generation, you only need to validate motion, camera, transitions, and lighting.

Step 7 - Keep a failure log

AI video punishes you for repeating mistakes, so write them down. Mine includes:

  • Camera path specified too aggressively
  • Too many character actions packed into one shot
  • Prompt description contradicting the reference image
  • Lighting and background descriptions fighting each other
  • One giant run-on prompt sentence

If you work with an AI coding/agent tool, put this log into its instructions or skill file and tell it to stop you from repeating them. Prompt-writing skill matters, but reducing your failure rate matters more.

Recommended pipelines by use case

Use casePipeline
BeginnerImage gen → Grok image-to-video → edit
Best cost/quality balanceImage gen → Grok motion test → Kling or Seedance via Higgsfield
High-end ad footageImage gen → Veo or Seedance → separate edit + sound
Music videoCharacter images → Grok scene tests → premium models for keepers → edit

Seven ways to waste credits (ask me how I know)

  1. Running a premium model on a half-written prompt
  2. Packing too many actions into one shot
  3. Generating long clips in one go
  4. Letting the image and the prompt describe different characters
  5. Endlessly "fixing" a generation that was never going to work
  6. Testing across multiple accounts without tracking free credits
  7. Maxing out resolution and audio on every draft

The last one is sneakier than it looks. Draft at low resolution to check motion and composition; re-render only the final picks in high quality.

Bottom line

AI video is not a one-click product; it is an iterative process of generating, discarding, and refining. That makes cheap iteration the most valuable feature a tool can have. My honest summary: Seedance and Kling are excellent — and too expensive to iterate on freely. So I test as much as possible on Grok, and re-render only the shots I already love on Higgsfield's premium models.

  1. Write the scene down
  2. Lock a reference image
  3. Test motion on a cheap model
  4. Pick the winners
  5. Final render on a premium model
  6. Music and SFX in the edit

Pricing, generation limits, and features of AI video platforms change frequently — check each service's current pricing before subscribing.

2023년 10월 19일 목요일

C# RichTextBox를 활용하여 이벤트 진행사항 업데이트하기

동기/비동기 모두 사용 가능.
   
private void _InsertMessage(string s)
{
    string strDatetime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
    if (RichTextBox.InvokeRequired)
    {
        RichTextBox.BeginInvoke(new Action(() => RichTextBox.AppendText("[ " + strDatetime + "] : ")));
        RichTextBox.BeginInvoke(new Action(() => RichTextBox.AppendText(s + System.Environment.NewLine)));
        RichTextBox.BeginInvoke(new Action(() => RichTextBox.ScrollToCaret()));
    }
    else
    {
        RichTextBox.AppendText("[ " + strDatetime + "] : ");
        RichTextBox.AppendText(s + System.Environment.NewLine);
        RichTextBox.ScrollToCaret();
    }
}   

C# PictureBox에서 마우스 우클릭으로 clipboard에 복사하기 기능 추가

 


private void PICVIEW_MouseClick(object sender, MouseEventArgs e)
{
	if (e.Button == MouseButtons.Right)
	{
		ContextMenu ctxM = new ContextMenu();
		Point mousePoint = new Point(e.X, e.Y);
		MenuItem m1 = new MenuItem();
		m1.Text = "Copy Image";
		
		ctxM.MenuItems.Add(m1);
		ctxM.Show(PICVIEW, mousePoint);
		
		m1.Click += (senders, es) =>
		{
			Clipboard.SetImage(m_PicViewImage); //m_PicViewImage ==> One of image file
		};
	}
}

2023년 10월 18일 수요일

여권 로마자 (영어 스펠링) 성(이름) 바뀌었을 때, 운전 면허증 (영문 이름) 변경

어릴 때 만들었던 여권에 표기된 내 성은 CHUNG. 

하지만 대학원 연구실에서 부터 그리고 논문 출판이 나올 때까지 줄 곧 Jung을 성으로 쓰고 있어 언젠가 바꾸고 싶다는 생각을 가지고 있었으나, 특수한 몇 가지 조건 없이 여권에 로마자 표기를 바꾸는 것은 꾀나 까다로운 일이다. 

하지만 로마자 표기를 바꿀 수 있는 몇 가지 요건 등이 있는데, 검색 결과 그래도 가장 확실한 것은 다음의 경우라고 한다. (그 외의 경우는 다음의 링크 참고 : https://www.passport.go.kr/home/kor/contents.do?menuPos=39 )


즉, 자녀의 여권을 원하는 성으로 표기해서 만들고 항공권을 예매해서 이를 증빙 서류로 활용하여 변경 신청하는 방법이다. 

이때 주의 할 것은 항공권을 구매할 때, 바꾸고자 하는 성으로 티켓을 끊어야 한다는 것이다. 

예를 들어 내가 바꾸고자 하는 성의 로마자 철자는 CHUNG-->에서 JUNG으로 바꾸고자 하는 것인데 항공권 구매할 때, JUNG으로 진행해야 한다는 사실. 아,,, 이것 때문에 바쁘시간 쪼개서 찾은 여권 민원실을 다른 날짜에 다시 방문해야 하는 아찔한 상황이 벌어질 뻔 했으나 재빨리 회사와 연계된 여행사에 연락해서 급하게 다시 항공권 티켓을 끊고, 겨우 같은 날 진행할 수 있었다. (다행스럽게도 찾아간 날이 목요일, 해당 구청이 저녁까지 운영하는 날이었다. )

우여곡절 끝에 서류를 모두 넣고, 담당 직원 분께서 외교부 심사가 길게는 2~3주가 걸릴 수 있다고 하셨으나 다행스럽게도 일주일 만에 외교부 심사가 완료되고 최종 여권이 나오기 까지 외교부 심사 1주일, 여권 처리기간 4일 (목/금/월/화) 만에 여권이 발급되었다.


여권 상에 성이 바뀌었으니 운전면허증 (작년 12월에 갱신하면서 영문면허증도 같이 발급 받았는데 CHUNG으로 발급을 받았었다. ㅠ.ㅜ) 도 재발급이 필요해서 바로 용인운전면허시험장으로 이동했고, 다행스럽게도 복잡한 절차 없이 재발급이 가능했다. 기타 필요한 서류 없이 구두로 설명 해드렸더니 아주 친절하게 빠르게 발급 해주셨다. 접수부터 운전면허 재발급까지 3분? ㅎㅎㅎ 와우~


이것으로 나의 성을 되찾을 수 있었으니~
별거 아니지만 굉장히 홀가분한 이기분~

2016년 8월 2일 화요일

C# Textbox example

if (k == 0)
                {
                    textBox1.Text = "c" + Convert.ToString(k) + "; 
                    x0, y0, R = " + Convert.ToString(cir[k].x0) + ",\t" +
                Convert.ToString(cir[k].y0) + ",\t" + Convert.ToString(cir[k].Radius);
                    textBox2.Text = "c" + Convert.ToString(k) + "; 
                    a1, a2, f1, f2 = " + Convert.ToString(a1_Round[k]) +
                        ", " + Convert.ToString(a2_Round[k]) + ", " + Convert.ToString(f1_Round[k]) + ", " + Convert.ToString(f2_Round[k]);
                }
                else
                {
                    textBox1.Text += System.Environment.NewLine + "c" + Convert.ToString(k) + "; 
                    x0, y0, R = " + Convert.ToString(cir[k].x0) + ",\t" +
                Convert.ToString(cir[k].y0) + ",\t" + Convert.ToString(cir[k].Radius);
                    textBox2.Text += System.Environment.NewLine + "c" + Convert.ToString(k) + "; 
                    a1, a2, f1, f2 = " + Convert.ToString(a1_Round[k]) +
                        ", " + Convert.ToString(a2_Round[k]) + ", " + Convert.ToString(f1_Round[k]) + ", " + Convert.ToString(f2_Round[k]);
                }
test
for (int x = 0; x < 5; x++)
{
}
\t  ==> tap 삽입
System.Environment.NewLine ==> 새 줄로 시작

2016년 2월 11일 목요일

C#에서 linear algebra 계산을 위한 무료 라이브러리

http://numerics.mathdotnet.com/

설치 방법은 간단합니다.

Visual C#을 실행시키신 후 라이브러리를 사용하려는 프로젝트에서

다음과 같이 패키지를 추가하시면 됩니다.


















패키지 관리자 콘솔에 다음과 같이 입력 후 Enter

PM> Install-Package MathNet.Numerics



아래는 콘솔을 사용한 간단한 예제 입니다.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Matrix A = DenseMatrix.OfArray(new double[,] {
                {1,1,1,1},
                {1,2,3,4},
                {4,3,2,1}});

            Vector[] nullspace = A.Kernel();

            // verify: the following should be approximately (0,0,0)
            //(A * (2 * nullspace[0] - 3 * nullspace[1]));
            Console.WriteLine(A * (2 * nullspace[0] - 3 * nullspace[1]));




            var C = Matrix.Build.DenseOfArray(new double[,] {
                { 3, 2, -1 },
                { 2, -2, 4 },
                { -1, 0.5, -1 }            });

            //Linear equation Example
            var b = Vector.Build.Dense(new double[] { 1, -2, 0 });
            var x = C.Solve(b);


            //Singular value decomposition
            var svd = C.Svd(true);
            
            Console.WriteLine(svd.U);
            Console.WriteLine(svd.W);
            Console.WriteLine(svd.VT);

            Console.ReadKey();
        }
    }
}





실행 결과

















이제는 매트랩 없이도 편하게 행렬식을 다룰 수 있겠군요.

이거 땜에 날아간 나의 시간들 ...   ㅠ.ㅜ

2016년 1월 27일 수요일

Visual C# (3) 서로 겹쳐지지 않는 원 그리기 (Non Overlapped Circle Drawing)

안녕하세요?

이곳에 포스팅을 한지도 벌써 일년이 넘었군요 ^^;; 

간만에 글을 남기긴 하지만 내용 자체는 지난 포스팅에 이어 계속 원을 그리는 것을 계속 해보도록 하겠습니다.

 이번에 포스팅할 내용은 원을 여러개 그리는데 서로 겹쳐지지 않게끔 그리는 것이 목표입니다. 이번에는 클래스를 이용해서 프로그램을 짤 건데요, 원의 중심점과 반지름 등을 이용하여 Circle 객체를 생성 한 후 각 객체가 서로 겹쳐지지 않게끔 검사를 해주고 최종적으로 각 원이 차지하는 픽셀을 White로 칠해주는 프로그램입니다.

 Circle 객체를 생성할 때에는 객체가 가지는 요소에 원의 중심점, 원의 반지름의 값을 설정하면 그려질 원이 차지하는 픽셀 영역의 집합을 계산하는 메소드를 넣는거 까지 Circle class가 하게 될 역할 입니다.

 그리고 CircleDraw class도 만들어 줄 건데요, 이 CircleDraw class는 원이 생성될 갯수를 설정해주면 각 객체가 생성될 때 마다 이전에 생성된 Circle 객체와 서로 겹쳐지지 않는 지를 검사하고 겹쳐지지 않는 것이 확인되면 최종적으로 원들이 차지하는 픽셀 영역의 집합에 새로운 원의 영역을 추가하는 것으로 마무리를 짓습니다.

뭐 코드는 안 보여드리고 쓸데없이 서두가 길었는데요,

일단 코드를 쭉 보시죠~


using System;
using System;
using System.Collections.Generic;
using System.Linq;


namespace NonOverlapCircleDrawing
{       
    class Circle
    {     
        double x0 { get; set; }
        double y0 { get; set; } //원의 중심 좌표
        double R { get; set; }  //원의 반경

        public HashSet hashCircleAreaIndex { get; set; }

        public Circle(double x, double y, double Radius)
        {
            this.x0 = x;
            this.y0 = y;
            this.R = Radius;
        }

        //원의 중심 좌표와 반경만 주어지면 원이 그려질 픽셀을 hashset에 넣어주는 기능을 하는 메소드
        //List, Array list 등을 사용할 수도 있지만 contain 검색 및 삭제 추가 시 시간이 더 많이 소요됨.
        public void CircleGeneration(int ImgW, int ImgH)
        {
            hashCircleAreaIndex = new HashSet();
            for (int Y = (int)(y0 - R); Y < (y0 + R); Y++)
            {
                for (int X = (int)(x0 - R); X < (x0 + R); X++)
                {
                    if (X >= ImgW || X < 0) continue;
                    if (Y >= ImgH || Y < 0) continue;
                    if ((X - x0) * (X - x0) + (Y - y0) * (Y - y0) < R * R) hashCircleAreaIndex.Add(ImgW * Y + X);
                }
            }
        }
    }


    class CircleDraw
    {        
        Circle[] cir { get; set; }
        double[] rawImage { get; set; }
        int ImgW { get; set; }
        int ImgH { get; set; }

        public List listCircleAreaIndex { get; set; } //중복되지 않는 Random Number를 생성하기 위해 꼭 필요함
        public HashSet hashCircleAreaIndex { get; set; } //Circle 객체를 차례로 생성함에 따라 각 객체가 차지하는 pixel index를 저장하는 hashset
        public HashSet hashTest; //listCircleAreaIndex와 연동하기 위한 hashset. List 하나로 처리해도 구동은 가능하나 contain 검색시나 foreach 구문 시 속도가 너무 느려 그 때만 이 hashset 이용

        public CircleDraw(int ImgW, int ImgH)
        {
            this.ImgW = ImgW;
            this.ImgH = ImgH;
        }

        //listCircleAreaIndex와 hashTest를 모든 픽셀 인덱스로 차례로 채워 넣기 위한 기능 수행
        public void ListGen()
        {
            int k = 0;
            listCircleAreaIndex = new List();
            hashTest = new HashSet();

            for (int j = 0; j < ImgH; j++)
            {
                for (int i = 0; i < ImgW; i++)
                {
                    listCircleAreaIndex.Add(k);
                    hashTest.Add(k);
                    k++;
                }
            }
        }

        //겹치지 않는 원을 그리기 위한 실제적인 기능을 하는 메소드
        //CircleNumber는 그리려는 원의 갯수 설정
        public void CircleGen(int CircleNumber)
        {
            cir = new Circle[CircleNumber];
            hashCircleAreaIndex = new HashSet();
            
            Random rnd = new Random(); // Random number를 사용하기 위한 구문

            for (int CirNo = 0; CirNo < CircleNumber; CirNo++)
            {
                RETRY: //순차적으로 원을 그릴때 이전의 원과 겹치게 되면 다시 되돌아가는 기능을 하게 하는 goto 구문
                int iRndNumber = rnd.Next(0, listCircleAreaIndex.Count); //list가 가진 숫자내에서 랜덤  넘버를 생성하기 위해 필요
                int iPositionIndex = listCircleAreaIndex[iRndNumber]; //list 내에서 임의의 인덱스 추출. 그리고 이 임의의 인덱스는 원의 중심 좌표로 변환. 

                //리스트에서 추출한 인덱스로부터 원의 중심 좌표 계산
                int x = iPositionIndex % ImgW;
                int y = iPositionIndex / ImgW;
                int R = rnd.Next(15, ImgH / 10); // 반지름에 대한 랜덤넘버 생성

                cir[CirNo] = new Circle(x, y, R); //생성된 원의 중심과 반지름을 이용하여 Circle 객체 생성
                cir[CirNo].CircleGeneration(ImgW, ImgH);

                //생성된 Circle 객체가 차지하는 픽셀마다 검사하면서 이전에 생성한 Circle 객체와 겹치는 부분이 있는지 확인.
                //만약 겹치는 부분이 없는 것이 확인되면 해당되는 각 픽셀 포지션을 기존의 리스트(여기선 우선 hashTest)에서 삭제.
                foreach (int i in cir[CirNo].hashCircleAreaIndex)
                {
                    if (CirNo != 0)
                    {
                        if (hashCircleAreaIndex.Contains(i)) goto RETRY;
                        else hashTest.Remove(i);
                    }
                }

                //변환된 hashTest 값을 리스트에 그대로 대입
                listCircleAreaIndex = hashTest.ToList();

                //끝으로 나중에 최종 그림을 그려줄 때 쓰일 원이 차지하는 픽셀의 집합(hashCircleAreaIndex)에 새로 생성된 원의 픽셀 인덱스 추가
                foreach (int i in cir[CirNo].hashCircleAreaIndex)
                {
                    hashCircleAreaIndex.Add(i);
                }
            }
      
        }
    }
}





그리고 이 class들을 이용할 main winform 코드 입니다.

using System;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;

namespace NonOverlapCircleDrawing
{
    public partial class MAIN_FORM : Form
    {
        public Graphics g;
        Bitmap bmpCircle;

        public MAIN_FORM()
        {
            InitializeComponent();
        }

        private void BTN_CIRCLE_GENERATE_Click(object sender, EventArgs e)
        {            
            int ImgW = 1024;
            int ImgH = 1024;
            int iCircleNumber = 100;

            bmpCircle = new Bitmap(ImgW, ImgH);

            g = Graphics.FromImage(bmpCircle);
            g.FillRectangle(Brushes.Black, 0, 0, bmpCircle.Width, bmpCircle.Height);

            CircleDraw cirDraw = new CircleDraw(ImgW, ImgH);
            cirDraw.ListGen();
            cirDraw.CircleGen(iCircleNumber);

            foreach(int i in cirDraw.hashCircleAreaIndex)
            {
                int x = i % ImgW;
                int y = i / ImgW;
                if (i >= ImgW * ImgH) return;
                bmpCircle.SetPixel(x, y, Color.White);
            }

            PIC_BOX1.Image = (Image)bmpCircle.Clone();
        }
    }
}




그리고 프로그램 구동 모습입니다.



간만에 포스팅을 했더니 설명이 너무 마구리라

혹시나 이상한 점이나 수정해야할 점 더 좋은 코멘트 있으면 글 남겨 주세요.

당연히 질문도 환영이구요~ ^^

읽어주셔서 감사합니다.



2014년 12월 27일 토요일

Visual C# (2) Random number를 이용하여 원을 그리고 picture Box에 image 띄우기

 안녕하세요? 이번 포스팅에서는 지난 포스팅에서 좀 더 발전 시켜 Random number를 이용하여 원을 그리고 그려진 원을 picture box에 올리는 프로그램 입니다.

 우선 작성한 전체 소스는 다음과 같습니다.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Circle_Draw_in_picturebox
{
    public partial class Form1 : Form
    {

        public Graphics g; //그림을 그리기 위한 도구인 Graphics 객체 생성
        public double pPi = Math.PI;    // Pi 값을 pPi에 할당.

        Bitmap canvas = new Bitmap(300,300); // 그림이 그려질 객체 생성. 여기서는 300 x 300 pixel로 생성
        Random rnd = new Random(); // Random number를 사용하기 위한 구문. 
        // method 내부가 아닌 class field 영역에서 선언했다는 점을 주목.
        // 이는 Random number의 확률 분포가 더 넓게 퍼지게 하기 위해 중요한 사항.
        // 더 자세한 사항은 다른 사이트 참조.

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            g = Graphics.FromImage(canvas);  //Graphics 객체에 그림이 그려질 canvas 할당
            g.FillRectangle(Brushes.Black, 0, 0, canvas.Width, canvas.Height); //canvas 배경을 Black으로 설정.

            //원을 그리기 위한 변수 설정
            double x0, y0;  //Center of the Circle
            double x1, y1;  //A point that Circle will be drawn.
            double R;       //Radius of circle
            double rad;     //Radian for drawing circle.
            double drad;    //Infinitesimal of radian 
            drad = pPi / 180 * 0.001;

            //원의 중심좌표와 반지름의 값을 Random number로 생성
            x0 = rnd.Next(10, 300); //10과 300 사이의 Random number 생성
            y0 = rnd.Next(10, 300);
            R = rnd.Next(10, 125); //10과 125 사이의 Random number 생성

            for (rad = 0; rad <= 2 * pPi; rad = rad + drad)
            {
                x1 = Math.Round(x0 + R * Math.Cos(rad), 0);
                y1 = Math.Round(y0 + R * Math.Sin(rad), 0);
                g.DrawLine(Pens.LightGoldenrodYellow, new Point((int)x0, (int)y0), new Point((int)x1, (int)y1));
            }

            // Drawn pictures are throw to the pictureBox1
            pictureBox1.Image = canvas;

            //x0, y0, R values are displayed in textBox1.
            textBox1.Text  = "x0 = " + Convert.ToString(x0);
            textBox1.Text += System.Environment.NewLine + "y0 = " + Convert.ToString(y0);
            textBox1.Text += System.Environment.NewLine + "R  = " + Convert.ToString(R);
            
        }
    }
}



결과는 다음과 같습니다.

보시는 것 처럼 Random number를 이용하여 원을 그리고 발생한 그 값 역시 textbox에 출력이 되도록 하였습니다.

그럼 이제 하나씩 자세히 뜯어 보도록 하겠습니다. 각각의 중요한 사항들은 주석에 적어 놓긴 했지만 다시한번 점검!!!


(1) 생성한 그림을 pictureBox에 띄우기.

아직 Image, Bitmap, Graphics 등등 각각의 라이브러리에 대해 개념 정립이 잘 되진 않았지만 주워들은 바에 의하면


  • Bitmap ==> 실제 픽셀을 가진 실체화된 객체를 생성하게 해주는 라이브러리.
  • Image ==> 추상적인 개념의 라이브러리로 Bitmap과 Graphics를 연결해주는 역할? 더 공부가 필요.
  • Graphics ==> 이미지 객체에 그림을 그려주는 도구로써의 역할을 하는 라이브러리.
  • 그래서 결국 그 절차는 다음과 같습니다.


   public Graphics g; //그림을 그리기 위한 도구인 Graphics 객체 생성

   Bitmap canvas = new Bitmap(Width,Height); // 그림이 그려질 객체 생성. 본 소스에서는 300 x 300 pixel로 생성

...

     g = Graphics.FromImage(canvas); //Graphics 객체에 그림이 그려질 canvas 객체 할당.
     g.FillRectangle(Brushes.Black, 0, 0, canvas.Width, canvas.Height); //
...
     g.DrawLine(Pens.LightGoldenrodYellow, new Point((int)x0, (int)y0), new Point((int)x1, (int)y1));
...
      pictureBox1.Image = canvas; //그려진 그림이(canvas) pictureBox에 출력될 수 있도록 할당.



Bitmap과 Graphics 객체를 각자 생성해주고, Bitmap 객체에 Graphics를 이용하여 원하는 그림을 그려넣어준 후, pictureBox에 Bitmap 객체(여기서는 canvas)를 할당해 줌.



(2) Random number creator (난수 생성)

 난수 생성 방법은 다음과 같습니다.
using System;
Random rnd = new Random(); // Random number를 사용하기 위한 구문
...
       //난수를 생성하여 변수에 대입.
       x0 = rnd.Next(10, 300);
       y0 = rnd.Next(10, 300);
       R = rnd.Next(10, 125);

Random 객체이름 = new Random(); 이와 같은 방법으로 선언 후
변수 = 객체이름.Next(범위); 의 방법으로 난수 생성 후 대입.

난수 생성에 대한 내용도 깊이 파자면 한도 끝도 없는 것 같지만... OTL

for loop 구문 등 반복적으로 난수를 사용해야 하는 경우에는 class field 단위에서 선언 후 method 안에서 개별적으로 사용해 주는 것이 좋다고 합니다.

자세한 내용은 아래 사이트 참조
http://topnanis.tistory.com/226



(3) textBox 사용하기

using System;
    //x0, y0, R values are displayed in textBox1.
     textBox1.Text  = "x0 = " + Convert.ToString(x0);
     textBox1.Text += System.Environment.NewLine + "y0 = " + Convert.ToString(y0);
     textBox1.Text += System.Environment.NewLine + "R  = " + Convert.ToString(R);



  • textBox1.Text = 문자열; 의 형태로 사용 가능합니다.
  • 내가 단순히 표시하고자 하는 문자는 따옴표" "를 사용하여 입력 
  • textBox1.Text += 문자열; 로 사용하는 이유는 +를 사용하지 않으면 기존의 내용이 삭제 되고 계속 refresh 됨. +를 해줌으로써 그 다음에 연결해서 출력됨.
  • System.Environment.NewLine을 넣어 주는 것은 [enter]를 쳐주는 것과 같은 기능. "\r\n"의 방법으로도 같은 효과를 발생시킴.
  • 여기서 중요!! 만약 프로그램 내부에서 사용한 변수를 출력하고 싶으면??  ==> Convert.ToString(변수)의 방법으로 출력을 해주어야 합니다. 왜냐하면 모니터 상에서 글자를 출력하기 위해서는 프로그램 내부에서 사용하던 숫자들을 (이들 숫자들은 0과1로 조합된 그야말로 순수한 숫자) 사람이 인식 가능한 [문자열]로 출력해 주기 위해서는 데이터형의 전환이 필요한데 이 기능을 해주는 것이 ToString 입니다.
  • 이외에도 문자열을 숫자로 바꿔주는 기능들도 있으니 더 찾아 보면 좋을 것 같네요. 

2014년 12월 24일 수요일

Visual C# (1) sin과 cos을 이용한 원 그리기 프로그램



요즘 회사 프로젝트 때문에 새롭게 visual c#을 공부하고 있습니다. 제가 공부하면서 작성하는 코드를 하나씩 포스팅 해보도록 하겠습니다. 참고로 저는 학부 때 c를 이용해서 기본적인 전산물리 문제를 풀어 본 경험이 있습니다.

아직 저도 배우는 단계라 하나씩 하나씩 수정 해 나가면서 프로그램을 계속 개선해 나가겠습니다.


우선은 sin 과 cos을 이용하여 원을 그리는 프로그램 입니다.

아주 단순한 코딩임에도 불구하고 제가 원하는 방식의 코드가 예상외로 찾기 힘들었습니다. 그래서 몇 가지 사이트를 참조해서 단순하게 새로 코딩을 하였습니다.

 제가 원하는 기능은 sin과 cos을 이용하여 원을 그리는 것인데, 단순히 원 테두리만 그리는 것이 아니라 안이 채워진 형태로 그리고자 했습니다.


 원을 그리는 방법은 다음의 사이트를 참조했습니다.

http://hhjae84.tistory.com/50
http://www.dreamincode.net/forums/topic/164701-drawing-shapes-with-sin-cos-values/




 제가 원하는 기능은 sin과 cos을 이용하여 원을 그리는 것인데, 단순히 원 테두리만 그리는 것이 아니라 속이 채워진 형태로 그리고자 했습니다. 이렇게 그리기 위해서 ellipse를 사용할 수도 있지만 이렇게 그리게 되면 theta에 따른 변화를 줄 수가 없어 배제 하였습니다.



x=R*cos(theta)
y=R*sin(theta)

위의 단순한 수식을 이용하였습니다. R은 원의 반지름이 입니다.

제가 원을 그린 방식은 원점을 지정하고 원점으로부터 거리가 R인 지점까지 일정한 theta만큼 변화시키며 선을 긋는 방식입니다. 사실 엄밀히 말하면 무수히 많은 선을 방사형으로 긋는 것인데 theta의 변화량이 점차 작아짐에 따라 원에 가까워지는 원리를 이용하였습니다. 이 방법은 추후에 변경해야 할지도 모르지만 현재론 이 방법이 제가 원하는 쓰임새엔 가장 근접한 것 같습니다.








다음은 실행 결과입니다.










-------------------------------------------------------------
[참고]
30도 간격으로 선을 그을 때



10도 간격으로 선을 그을 때



5도 간격으로 선을 그을 때


1도 간격으로 선을 그을 때