How can I fill inbetween these Green/Red Lines? - line

I can't for the life of me figure out how to fill in between these horizontal lines.
I currently have 2 horizontal lines, & would love to fill them in with color or a gradient.
It's not the normal code, as these are formatted line.new...
Anyone knows how?
I would love to color these zones with a gradient, but can't figure out how to tell the code these exact horizontal lines
//#version=4
study(shorttitle = "[CC] Price Zone", title="[CC] Price Zone", overlay=true, max_bars_back=500)
// ●─────────────────────────────────────────────────────────────────── ∴ ───────────────────────────────────────────────────────────────────● }
maxBarsBack = 500
line bullEngulfOpen = na
line bullEngulfLow = na
//line bullEngulf50 = na
line bearEngulfOpen = na
line bearEngulfHigh = na
//line bearEngulf50 = na
previousRange = open[1] - close[1]
isBullEngulf = previousRange > 0 and close > open[1]
isBearEngulf = previousRange < 0 and close < open[1]
//colors//
coloropen = color.rgb(76,187,23,30)
colorwick = color.rgb(194,24,7,10)
if isBullEngulf
bullEngulfOpen := line.new(bar_index - 1, open[1], bar_index, open[1], extend=extend.right, color=coloropen)
bullEngulfLow := line.new(bar_index - 1, low < low[1] ? low : low[1],bar_index, low < low[1] ? low : low[1], extend=extend.right, color=colorwick)
//bullEngulf50 := line.new(bar_index - 1, ((high[1]+low[1])/2), bar_index, ((high[1]+low[1])/2), extend=extend.right, color=color.blue, style=line.style_dotted)
if isBearEngulf
bearEngulfOpen := line.new(bar_index - 1, open[1], bar_index, open[1], extend=extend.right, color=coloropen)
bearEngulfHigh := line.new(bar_index - 1, high > high[1] ? high : high[1], bar_index, high > high[1] ? high : high[1], extend=extend.right, color=colorwick)
// bearEngulf50 := line.new(bar_index - 1, ((low[1]+high[1])/2), bar_index, ((low[1]+high[1])/2), extend=extend.right, color=color.fuchsia, style=line.style_dotted)
//color gray when finished//
grayopen = color.rgb(49,51,53,10)
graywick = color.rgb(84,86,88,10)
var maxNumberOfEngulfings = 10
bullEngulfingCount = 0
for i = 1 to maxBarsBack
if not na(bullEngulfOpen[i])
if low < line.get_y1(bullEngulfLow[i])
line.delete(bullEngulfOpen[i])
line.delete(bullEngulfLow[i])
// line.delete(bullEngulf50[i])
continue
if low < line.get_y1(bullEngulfOpen[i])
line.set_color(bullEngulfOpen[i], grayopen)
line.set_color(bullEngulfLow[i], graywick)
// line.set_color(bullEngulf50[i], color.gray)
bullEngulfingCount := bullEngulfingCount + 1
if bullEngulfingCount > maxNumberOfEngulfings
line.delete(bullEngulfOpen[i])
line.delete(bullEngulfLow[i])
// line.delete(bullEngulf50[i])
bearEngulfingCount = 0
for i = 1 to maxBarsBack
if not na(bearEngulfOpen[i])
if high > line.get_y1(bearEngulfHigh[i])
line.delete(bearEngulfOpen[i])
line.delete(bearEngulfHigh[i])
// line.delete(bearEngulf50[i])
continue
if high > line.get_y1(bearEngulfOpen[i])
line.set_color(bearEngulfOpen[i], grayopen)
line.set_color(bearEngulfHigh[i], graywick)
// line.set_color(bearEngulf50[i], color.gray)
bearEngulfingCount := bearEngulfingCount + 1
if bearEngulfingCount > maxNumberOfEngulfings
line.delete(bearEngulfOpen[i])
line.delete(bearEngulfHigh[i])
// line.delete(bearEngulf50[i])

Related

Syntax Error Fix Required for the (Updated) Filtered Connors RSI in AFL AmiBroker

Here is the updated AFL for "Filtered Connors RSI" -
_SECTION_BEGIN("Filtered Connors RSI Final");
ma_length = Param("MA Length", 14, 3, 100);
c_length = Param("C Length", 3, 1, 100);
ud_length = Param("UD Length", 2, 1, 100);
roc_length = Param("ROC Length", 100, 1, 100);
function updown(input)
{
s = Close;
isEqual = s == Ref(s, -1);
isGrowing = s > Ref(s, -1);
ud = StaticVarGet("UD Self-Referencing", align=True);
ud = IIf(isEqual == 0, isGrowing, IIf(Nz(Ref(ud, -1)) <= 0, 1, Nz(Ref(ud, -1) + 1), IIf(Nz(Ref(ud, -1)) >= 0, -1, Nz(Ref(ud, -1) - 1)), Null);
return ud;
}
function RSIt(ARRAY, range)
{
return RSIa(Close, c_length);
}
function CRSI(Close, c_length, ud_length, roc_length)
{
updn = RSIa(updown(Close), c_length);
tRSI = RSIa(Close, c_length);
updownrsi = RSIt(updn, ud_length);
ptrk = PercentRank(ROC(Ref(Close, -1)), roc_length);
return (tRSI + updownrsi + ptrk)/3;
}
rsi_open = crsi( Open, c_length, ud_length, roc_length);
rsi_high = crsi( High, c_length, ud_length, roc_length);
rsi_low = crsi( Low, c_length, ud_length, roc_length);
rsi_close = crsi( Close, c_length, ud_length, roc_length);
function HaClose(O, H, L, C)
{
return (O + H + L + C) / 4;
}
source = HaClose(rsi_open, rsi_high, rsi_low, rsi_close);
fcrsi = TEMA(source, ma_length);
PlotGrid(70, colorGreen, pattern=10, width=1, label=True);
PlotGrid(60, colorPlum, pattern=9, width=1, label=True);
PlotGrid(50, colorBrown, pattern=9, width=1, label=True);
PlotGrid(40, colorPlum, pattern=9, width=1, label=True);
PlotGrid(30, colorRed, pattern=10, width=1, label=True);
Plot(fcrsi, "Filtered Connors RSI", colorBlue, styleLine|styleThick);
//Rescaling
Plot(100, "", colorWhite,styleLine|styleNoDraw|styleNoLabel);
Plot(0, "", colorWhite,styleLine|styleNoDraw|styleNoLabel);
_SECTION_END();
Here is the error -
Error 31. Syntax error, unexpected ';', expecting ')' or','
The line of pine script code based on the "Ternary Operator" I am trying to code with the "IIf" function in AFL is as follows -
ud := isEqual ? 0 : isGrowing ? (nz(ud[1]) <= 0 ? 1 : nz(ud[1])+1) :
(nz(ud[1]) >= 0 ? -1 : nz(ud[1])-1)
The pine script code snippet consists the whole function is as follows -
updown(float s) =>
isEqual = s == s[1]
isGrowing = s > s[1]
ud = 0.0
ud := isEqual ? 0 : isGrowing ? (nz(ud[1]) <= 0 ? 1 : nz(ud[1])+1) : (nz(ud[1]) >= 0 ? -1 : nz(ud[1])-1)
ud
Please help me to fix this. Regards.

I want to find the highest price since entry in pine script?

I want to find the highest price and exit when current price is lower than highest price. The code to find the highest price is copied from here. how can I make a simpler code that finds highest price since entry? I also want to close the deal if current price is lower than a specific price. Please help me.
// SETTING //
length1=input(1)
length3=input(3)
length7=input(7)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=(low>upper and BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit,10)
// - INPUTS
ShowPivots = input(true, title="Show Pivot Points")
ShowHHLL = input(true, title="Show HH,LL,LH,HL markers on Pivots Points")
left = input(5, minval=1, title="Pivot Length Left Hand Side")
right = input(5, minval=1, title="Pivot Length Right Hand Side")
ShowSRLevels = input(true, title="Show S/R Level Extensions")
maxLvlLen = input(0, minval=0, title="Maximum S/R Level Extension Length (0 = Max)")
ShowChannel = input(false, title="Show Levels as a Fractal Chaos Channel")
//
ShowFB = input(true, title="Show Fractal Break Alert Arrows")
// Determine pivots
pvtLenL = left
pvtLenR = right
// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
pvthi = pvthi_
pvtlo = pvtlo_
// ||-----------------------------------------------------------------------------------------------------||
// ||--- Higher Highs, Lower Highs, Higher Lows, Lower Lows -------------------------------------------||
valuewhen_1 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_2 = valuewhen(pvthi, high[pvtLenR], 0)
higherhigh = na(pvthi) ? na : valuewhen_1 < valuewhen_2 ? pvthi : na
valuewhen_3 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_4 = valuewhen(pvthi, high[pvtLenR], 0)
lowerhigh = na(pvthi) ? na : valuewhen_3 > valuewhen_4 ? pvthi : na
valuewhen_5 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_6 = valuewhen(pvtlo, low[pvtLenR ], 0)
higherlow = na(pvtlo) ? na : valuewhen_5 < valuewhen_6 ? pvtlo : na
valuewhen_7 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_8 = valuewhen(pvtlo, low[pvtLenR ], 0)
lowerlow = na(pvtlo) ? na : valuewhen_7 > valuewhen_8 ? pvtlo : na
// If selected Display the HH/LL above/below candle.
plotshape(ShowHHLL ? higherhigh : na, title='HH', style=shape.triangledown, location=location.abovebar, color=color.new(color.green,50), text="HH", offset=-pvtLenR)
plotshape(ShowHHLL ? higherlow : na, title='HL', style=shape.triangleup, location=location.belowbar, color=color.new(color.green,50), text="HL", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerhigh : na, title='LH', style=shape.triangledown, location=location.abovebar, color=color.new(color.red,50), text="LH", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerlow : na, title='LL', style=shape.triangleup, location=location.belowbar, color=color.new(color.red,50), text="LL", offset=-pvtLenR)
plot(ShowPivots and not ShowHHLL ? pvthi : na, title='High Pivot', style=plot.style_circles, join=false, color=color.green, offset=-pvtLenR, linewidth=3)
plot(ShowPivots and not ShowHHLL ? pvtlo : na, title='Low Pivot', style=plot.style_circles, join=false, color=color.red, offset=-pvtLenR, linewidth=3)
//Count How many candles for current Pivot Level, If new reset.
counthi = 0
countlo = 0
counthi := na(pvthi) ? nz(counthi[1]) + 1 : 0
countlo := na(pvtlo) ? nz(countlo[1]) + 1 : 0
pvthis = 0.0
pvtlos = 0.0
pvthis := na(pvthi) ? pvthis[1] : high[pvtLenR]
pvtlos := na(pvtlo) ? pvtlos[1] : low[pvtLenR]
hipc = pvthis != pvthis[1] ? na : color.new(color.red,50)
lopc = pvtlos != pvtlos[1] ? na : color.new(color.green,50)
// Show Levels if Selected
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, linewidth=1, offset=-pvtLenR , title="Top Levels",style=plot.style_circles)
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, linewidth=1, offset=-pvtLenR , title="Bottom Levels",style=plot.style_circles)
// Show Levels as a Fractal Chaos Channel
plot(ShowSRLevels and ShowChannel ? pvthis : na, color=color.green, linewidth=1, style=plot.style_stepline, offset=0, title="Top Chaos Channel", trackprice=false)
plot(ShowSRLevels and ShowChannel ? pvtlos : na, color=color.red, linewidth=1, style=plot.style_stepline, offset=0, title="Bottom Chaos Channel", trackprice=false)
// //
float fixedHH = fixnan(higherhigh)
// add offset = -pvtLenR to move the plot to the left and match the HH points.
plot(fixedHH)
bool lowerThanHH = close < fixedHH
float closeHHDiff = abs(fixedHH - close)
if barstate.islast
label.new(bar_index, high + 3*tr, tostring(closeHHDiff), xloc.bar_index, color = color.gray, style = label.style_label_down)
// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60)
strategy.entry("Long",strategy.long,1)
if (higherhigh*0.80==close)`enter code here`
strategy.close("Long",1)
imInATrade = strategy.position size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
The code above finds the highest price after entry or when you're in a trade.

Tradingview pine editor. Issue with ATR TP/SL coding from entry

I need to code Take profit and Stop loss with Average true range from the past. I have an issue my code is calculating latest ATR and i cannot find a way to lock ATR number from the entry. ATR is calculating after candle close that means while candle is active it doesn't exist. Adding picture where I have marked what I'm looking for and what pine is calculating.
Paint shows what I'm looking for, original pine shows code calculations
//#version=2
strategy("Heiwa",initial_capital=1000,default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.15, overlay=true)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
sensitivity = input(200, title="Sensitivity")
fastLength=input(20, title="FastEMA Length")
slowLength=input(40, title="SlowEMA Length")
channelLength=input(20, title="BB Channel Length")
mult=input(2.0, title="BB Stdev Multiplier")
deadZone=input(20, title="No trade zone threshold")
calc_macd(source, fastLength, slowLength) =>
fastMA = ema(source, fastLength)
slowMA = ema(source, slowLength)
fastMA - slowMA
calc_BBUpper(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis + dev
calc_BBLower(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis - dev
t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength))*sensitivity
t2 = (calc_macd(close[2], fastLength, slowLength) - calc_macd(close[3], fastLength, slowLength))*sensitivity
e1 = (calc_BBUpper(close, channelLength, mult) - calc_BBLower(close, channelLength, mult))
//e2 = (calc_BBUpper(close[1], channelLength, mult) - calc_BBLower(close[1], channelLength, mult))
trendUp = (t1 >= 0) ? t1 : 0
trendDown = (t1 < 0) ? (-1*t1) : 0
Waddardtdis = input(50, minval=1)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
atrBandDays = input(15, minval=1, title="Days for ATR", type=integer)
atrBand = atr(atrBandDays)
atrPlus1 = close + atrBand
atrPlus2 = close + atrBand*2
atrPlus3 = close + atrBand*3
atrStop = close - atrBand*2
plot(atrPlus1, color=green)
plot(atrPlus2, color=orange)
plot(atrPlus3, color=red)
plot(atrStop, color=blue)
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
haTicker = heikinashi(tickerid)
haOpen = security(haTicker, period, open)
haClose = security(haTicker, period, close)
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
longCondition = haClose > haOpen and haOpen > haClose[1] and trendUp>e1
exitCondition = haClose < haOpen and trendDown>Waddardtdis
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("TP1", "Long", qty_percent = 60, limit=atrPlus1)
strategy.exit("TP2", "Long", qty_percent = 20, limit=atrPlus2)
strategy.exit("TP3", "Long", qty_percent = 20, limit=atrPlus3)
strategy.exit("SL", "Long", stop = atrStop)
strategy.close ( "Long", when = exitCondition)
I'd just preserve the atr value at entry, like that:
entryAtr = entryAtr[1]
if (longCondition)
strategy.entry("Long", strategy.long)
entryAtr := atrBand // save the value to use it for exit

Identifying Peaks from Line Profile

I would like to ask if it is possible to locate the position of every maxima and minima of an intensity profile on DM.
How do I come up with a simple script that identifies the positions of the peaks in the example below?
Here's a screenshot of line intensity profile of a STEM image along the Y-direction:
If you want to filter for "strict" local maxima, then you can easily do this with image expressions and the conditional "tert" operator. The following example illustrates this:
image CreateTestSpec( number nChannels, number nPeaks, number amp, number back )
{
image testImg := RealImage( "TestSpec", 4, nChannels )
testImg = amp * cos( PI() + 2*PI() * nPeaks * icol/(iwidth-1) )
testImg += back
testImg = PoissonRandom( testImg )
return testImg
}
image FilterLocalMaxima1D( image spectrumIn, number range )
{
image spectrumOut := spectrumIn.ImageClone()
for( number dx = -range; dx<=range; dx++ )
spectrumout *= ( spectrumIn >= offset(spectrumIn,dx,0) ? 1 : 0 )
spectrumout.SetName("Local maxima ("+range+") filtered")
return spectrumOut
}
image test1 := CreateTestSpec(256,10,1000,5000)
image test2 := FilterLocalMaxima1D(test1,3)
test1.ShowImage()
test2.ShowImage()
However, considering noise (also in your example image), you might want to perform fits around these "local maxima" to ensure you're really getting what you want. The data from above is then only the starting point for that.
Also: Sometimes you can get away with first averaging your data and then finding the local maxima, instead of doing real data fitting in each peak. This works in particular, if you "know" the width of your real peaks rather well.
This would be the example:
image CreateTestSpec( number nChannels, number nPeaks, number amp, number back )
{
image testImg := RealImage( "TestSpec", 4, nChannels )
testImg = amp * cos( PI() + 2*PI() * nPeaks * icol/(iwidth-1) )
testImg += back
testImg = PoissonRandom( testImg )
return testImg
}
image FilterLocalMaxima1D( image spectrumIn, number range )
{
image spectrumOut := spectrumIn.ImageClone()
for( number dx = -range; dx<=range; dx++ )
spectrumout *= ( spectrumIn >= offset(spectrumIn,dx,0) ? 1 : 0 )
spectrumout.SetName("Local maxima ("+range+") filtered")
return spectrumOut
}
image FilterLocalMaxima1DAveraged( image spectrumIn, number range )
{
image avSpectrum := spectrumIn.ImageClone()
avSpectrum = 0
for( number dx = -range; dx<=range; dx++ )
avSpectrum += offset(spectrumIn,dx,0)
avSpectrum *= 1/(2*range+1)
image spectrumOut := spectrumIn.ImageClone()
for( number dx = -range; dx<=range; dx++ )
spectrumout *= ( avSpectrum >= offset(avSpectrum,dx,0) ? 1 : 0 )
spectrumout.SetName("Local maxima ("+range+") filtered, average")
return spectrumOut
}
image test1 := CreateTestSpec(256,10,1000,5000)
image maxPeaks := FilterLocalMaxima1D(test1,3)
image maxPeaksAv := FilterLocalMaxima1DAveraged(test1,3)
test1.ShowImage()
test1.ImageGetImageDisplay(0).ImageDisplayAddImage( maxPeaks, "local max" )
test1.ImageGetImageDisplay(0).ImageDisplayAddImage( maxPeaksAv, "local max from Average" )
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceComponentColor( 0, 1, 0.7, 0.7, 0.7 )
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceDrawingStyle( 1, 2)
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceComponentColor( 1, 1, 1, 0, 0 )
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceTransparency( 1, 1, 0.7 )
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceDrawingStyle( 2, 2)
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceComponentColor( 2, 1, 0, 1, 0 )
test1.ImageGetImageDisplay(0).LinePlotImageDisplaySetSliceTransparency( 2, 1, 0.7 )
The easiest way is to use 1-point (or 2-point) neighborhood to decide, whether center is minimum (maximum). See pseudo code below:
// assume 0 <= x <= maxX, y(x) is value at point x, radius is 1
x = 1;
while (x + 1 <= maxX)
{
if (y(x) > y(x-1) and y(x) > y(x+1))
// we found a maximum at x
if (y(x) < y(x-1) and y(x) < y(x+1))
// we found a minimum at x
x = x + 1
}
For 2-point neighborhood maximum condition could be
if (y(x) > y(x-1) and y(x-1) >= y(x-2) and y(x) > y(x+1) and y(x+1) >= y(x+2))
Note >= here. You may use > instead.
Note that above approach won't find maximum in case two consecutive x have the same value y e.g. for y(0) = 0, y(1) = 1, y(2) = 1, y(3) = 0 it won't find maximum neither for x = 1, nor for x = 2.

Convert an image into polaroid filter

I am trying to convert an image into polaroid filter in the following way:
int m_width = self.size.width;
int m_height = self.size.height;
uint32_t *rgbImage = (uint32_t *) malloc(m_width * m_height * sizeof(uint32_t));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(
rgbImage,
m_width,
m_height,
8,
m_width * 4,
colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast
);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetShouldAntialias(context, NO);
CGContextDrawImage(context, CGRectMake(0, 0, m_width, m_height), [self CGImage]);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
// now convert to grayscale
uint8_t *m_imageData = (uint8_t *) malloc(m_width * m_height);
for(int y = 0; y < m_height; y++)
{
for(int x = 0; x < m_width; x++)
{
uint32_t rgbPixel=rgbImage[y*m_width+x];
uint32_t redIn = 0, greenIn = 0,blueIn = 0,max = 0,min = 0,chroma = 0,hue = 0,saturation = 0,redOut = 0,greenOut = 0,blueOut = 0;
redIn = (rgbPixel>>24)&255;
greenIn = (rgbPixel>>16)&255;
blueIn = (rgbPixel>>8)&255;
//NSLog(#"redIn %u greenIn %u blueIn %u",redIn,greenIn,blueIn);
max = redIn > greenIn ? redIn > blueIn ? redIn : blueIn : greenIn > blueIn ? greenIn : blueIn;
min = redIn < greenIn ? redIn < blueIn ? redIn : blueIn : greenIn < blueIn ? greenIn : blueIn;
chroma = max - min;
if(chroma != 0)
{
if(max == redIn)
hue = ((greenIn - blueIn) / chroma) %6 ;
else if(max == greenIn)
hue = ((blueIn - redIn)/chroma) + 2;
else if(max == blueIn)
hue = ((redIn - greenIn)/chroma) + 4;
hue = (hue+20)%6;
if(chroma != 0)
saturation = chroma / max;
if(hue >= 0 && hue < 1)
{
redOut = chroma + max - chroma;
greenOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
blueOut = 0 + max - chroma;
}
else if(hue >= 1 && hue < 2)
{
redOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
greenOut = chroma + max - chroma;
blueOut = 0 + max - chroma;
}
else if(hue >= 2 && hue < 3)
{
redOut = 0 + max - chroma;
greenOut = chroma + max - chroma;
blueOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
}
else if(hue >= 3 && hue < 4)
{
redOut = 0 + max - chroma;
greenOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
blueOut = chroma + max - chroma;
}
else if(hue >= 4 && hue < 5)
{
redOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
greenOut = 0 + max - chroma;
blueOut = chroma + max - chroma;
}
else if(hue >= 5 && hue < 6)
{
redOut = chroma + max - chroma;
greenOut = 0 + max - chroma;
blueOut = chroma * (1 - abs((hue % 2) - 1)) + max - chroma;
}
}
//NSLog(#"redOut %u greenOut %u blueOut %u",redOut,greenOut,blueOut);
m_imageData[y*m_width+x]=redOut + greenOut + blueOut;
}
}
free(rgbImage);
// convert from a gray scale image back into a UIImage
uint8_t *result = (uint8_t *) calloc(m_width * m_height *sizeof(uint32_t), 1);
// process the image back to rgb
for(int i = 0; i < m_height * m_width; i++)
{
result[i*4]=0;
int val=m_imageData[i];
result[i*4+1]=val;
result[i*4+2]=val;
result[i*4+3]=val;
}
free(m_imageData);
// create a UIImage
colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(result,
m_width,
m_height,
8,
m_width * sizeof(uint32_t),
colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast
);
CGImageRef image = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
#ifdef kNYXReturnRetainedObjects
UIImage* resultUIImage = [[UIImage alloc] initWithCGImage:image];
#else
UIImage *resultUIImage = [UIImage imageWithCGImage:image];
#endif
CGImageRelease(image);
free(result);
return resultUIImage;
but I'm not getting the polaroid image after execution this code.
What's the problem in this code or can you suggest me some other way.
The most obvious problem with the code is that, at the end of the method, you create a drawing context, do nothing in it, then take an image from it and return that as a UIImage. This will be blank, presumably. I think you're trying to obtain the image that is held in the data in result - I think you need to look at CGImageCreate instead rather than setting up a new context.
See here for information on creating a data provider with raw data, which you will need to pass to CGImageCreate. This all does look rather complicated.