Getting black and white image when doing rotation? - rgb

I want to rotate my image by 45 degree. I have defined a function for the same. When I run it over my RGB images, it is getting saved as grayscale images?
def rotateImage(image, angle):
row,col = image.shape
center=tuple(np.array([row,col])/2)
rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
new_image = cv2.warpAffine(image, rot_mat, (col,row))
return new_image
rotate_img_path = '../data/rotate_45_img'
rotate_mask_path = '../data/rotate_45_mask'
real_img_path = '../data/img'
real_mask_path = '../data/mask'
for img in os.listdir(real_img_path):
edge_img = cv2.imread(os.path.join(real_img_path,img))
edges = rotateImage(edge_img, 45)
cv2.imwrite(os.path.join(rotate_img_path, img), edges)
print("Finished Copying images")
for img in os.listdir(real_mask_path):
edge_img = cv2.imread(os.path.join(real_mask_path,img))
edges = rotateImage(edge_img, 45)
cv2.imwrite(os.path.join(rotate_mask_path, img), edges)
# cv2.imwrite('edge_' + '.jpg', edges)
print("Finished Copying masks")

A clue here may be
row,col = image.shape
which would raise an error if image was three dimensional (i.e., in color with separate channels for B, G, and R) instead of two (i.e., grayscale). Unless you're reading RGB images with code not shown here, this suggests that your images are already grayscale.

Related

getattribute in OSL is not giving expected results

I'm working on a custom OSL shader for Maya. I'm adding attributes to the shape node of objects and using getattribute() in my OSL code to manipulate those attributes. I have attributes for color correct, base color, rim width and rim color. (the last 2 are for facing ratio). My OSL always compiles and I'm always able to connect it to the material I'm using. But every time I check if it's working in the Arnold render view, my sliders on my attributes don't do anything. The goal is to have an image file connected to the base color of the material and have the color correct node affect base color (which would affect the texture file)
At first I thought my problem was I was trying to do too much in a single OSL node (I was using getattribute for all of the attributes I listed above). So I tried isolating it to just the color correct attribute and still nothing. Is anyone familiar with OSL and can help me?
This is what my OSL code is for color correct:
shader
colorCorrect
(
float modifier = 1[[float min = 0, float max = 72]],
color bob = 0,
output color result = 0
)
{
color temp = transformc("rgb", "hsv", bob);
temp[0] = temp[0] * modifier;
result = transformc("hsv", "rgb", temp);
}
This is what my OSL code is for facing ratio:
shader
Velvet(
float rim_width = 0.2
[[
string label = "Rim Width",
]],
color basecolor = color(1,1,1)
[[
string label = "Base Color",
string widget = "checkBox",
]],
color rimcolor = color(1,0,0)
[[
string label = "Rim Color",
]],
output color resultRGB = 0,
output float resultF = 0)
{
vector i = normalize(I);
vector n = normalize(N);
float d = fabs(dot(-i, n));
d = smoothstep(rim_width, 1.0, d);
getattribute("base_color", resultRGB = mix(rimcolor, basecolor, d));
getattribute("rim_width", resultF = d - 0.5);
}

I was working on this project for real time face mask detection, but the i am facing an error cannot reshape array of size 2 into shape (1,100,100,1)

Please tell me so as to what should i do to solve this problem or what values should i put to solve this problem
while(True):
ret,img = source.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces=face_clsfr.detectMultiScale(gray,1.3,5)
for x,y,w,h in faces:
face_img = gray[y:y+w,x:x+w]
resized = cv2.resize(face_img,(100,100))
normalized=resized/255,0
reshaped = np.reshape(normalized, (1,100,100,1))
result=model.predict(reshaped)
label=np.argmax(result,axis=1)[0]
cv2.rectangle(img,(x,y),(x+w,y+h), colordict[label],2)
cv2.rectangle(img,(x,y-40),(x+w,y), colordict[label],-1)
cv2.putText(img,labels_dict[label], (x,y-10), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)
cv2.imshow('Frame',img)
key=cv2.waitKey(1)
if(key=='q'):
break
cv2.destroyAllWindows()
source.release
You change the array type of image to a tuple in:
normalized = resized/255,0
change to:
normalized = resized/255

Swift - Create circle and add to array

I've been looking for a little while on how to create a circle in Swift, but it seems quite complicated. I want to create a circle at run time, with a specified x and y, and width and height. I then want to add this circle to an array where I can create more circles and add to it.
How do I do this?
Edit: This is what I've tried so far:
var center : CGPoint = touchLocation
var myContext : CGContextRef = UIGraphicsGetCurrentContext()
let color : [CGFloat] = [0, 0, 1, 0.5]
CGContextSetStrokeColor (myContext, color);
CGContextStrokeEllipseInRect (myContext, CGRectMake(touchLocation.x, touchLocation.y, 20, 20));
touchLocation is the location of the users finger. This crashes on execution on this line:
var myContext : CGContextRef = UIGraphicsGetCurrentContext()
The error says "Unexpectedly found nil while unwrapping an Optional value
Also, this doesn't allow me to add the circle to an array, because I don't know what variable type it is.
There are many ways to draw a circle, here is a snippet that I have been hacking with:
func circleWithCenter(c:CGPoint, radius r:CGFloat,
strokeColor sc: UIColor = UIColor.blackColor(),
fillColor fc: UIColor = UIColor.clearColor()) -> CAShapeLayer {
var circle = CAShapeLayer()
circle.frame = CGRect(center:c, size:CGSize(width:2*r, height:2*r))
circle.path = UIBezierPath(ovalInRect:circle.bounds).CGPath
circle.fillColor = fc.CGColor
circle.strokeColor = sc.CGColor
circle.fillColor = fc == UIColor.clearColor() ? nil : fc.CGColor
return circle
}
Note that I extended CGRect (using Swift specific features) to add a initializer that takes a center, but that is not material to your question.
Your code is not "creating" a circle as an object, it is attempting to draw one in the graphics context. What you need to do is to create a bezier path object, draw into that and save the path in your array. Something like:
var circleArray = [CGMutablePathRef]()
// ...
let path: CGMutablePathRef = CGPathCreateMutable()
CGPathAddArc(path, nil, touchLocation.x, touchLocation.y, radius, 0, M_PI * 2, true)
circleArray += [path]
You then need to stroke the path(s) in your draw routine.

Saving GeoTiff with color scheme

I am trying to save a numpy array output as a GeoTiff, and have the code running mostly successfully, but the output image has a sepia-toned scale for the data (instead of a normal color scheme like my code produces for the image), and a black background (instead of the white/no-data background that my code produces for the image).
Here's the code for saving my array to a GeoTiff. Can I add a line in somewhere about making no-data = 0, and making the data scheme be colored?
from osgeo import gdal, osr, ogr, os
from gdalconst import *
def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
cols = array.shape[1]
rows = array.shape[0]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
driver = gdal.GetDriverByName( 'GTiff' )
outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Float32)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(array)
# outRaster = driver.Create( 'CORDC_GTIFF/working_CA.tiff', 300, 300, 1, gdal.GDT_Int32)
proj = osr.SpatialReference()
proj.ImportFromEPSG(4326)
outRaster.SetProjection(proj.ExportToWkt())
# geotransform = (1,0.1,0,40,0,0.1)
rasterOrigin = (-127,42)
pixelWidth = .01
pixelHeight = .01
newRasterfn = 'CORDC_GTIFF/cordc_working_CA.tif'
array = np.array(spd)
reversed_arr = array[::-1] # reverse array so the tif looks like the array
array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,reversed_arr) # convert array to raster
You can set the no data value using the band's SetNoDataValue method:
outband = outRaster.GetRasterBand(1)
outband.SetNoDataValue(0)
outband.WriteArray(array)
Areas matching the no data value should then be displayed as transparent

Rotating CGPoints; CIVector CGAffineTransform?

I have 4 CGPoints that form an irregular figure. How can I rotate that figure 90-degrees and get the new CGPoints?
FWIW, I was able to "fake" this when the figure is a CGRect by swapping origin.x and origin.y, and width and height. Will I need to do something similar (calculating distance/direction between points) or is there a AffineTransform I can apply to a CIVector?
Hints and/or pointers to tutorials/guides welcome.
Skippable Project Background:
Users will take pictures of documents and the app will OCR them. Since users have a great deal of trouble getting a non-skewed image, I allow them to create a 4-point figure around the text body and the app skews that back to a rectangle. The camera images coming in are CIImages and so have their origin already in lower-left, so the 4-point figure must be rotated from the UIView to match...
For the record, I used CGAffineTransforms to rotate the points:
CGAffineTransform t1 = CGAffineTransformMakeTranslation(0, cropView.frame.size.height);
CGAffineTransform s = CGAffineTransformMakeScale(1, -1);
CGAffineTransform r = CGAffineTransformMakeRotation(90 * M_PI/180);
CGAffineTransform t2 = CGAffineTransformMakeTranslation(0, -cropView.frame.size.height);
CGPoint a = CGPointMake(70, 23);
a = CGPointApplyAffineTransform(a, t1);
a = CGPointApplyAffineTransform(a, s);
a = CGPointApplyAffineTransform(a, r);
a = CGPointApplyAffineTransform(a, t2);
&c. for the other points.

Resources