Why does my loop export only one integer in the string? - loops

I am trying to Save each integer in string.ascii_uppercase as an image file.
The loop only saves one image (the letter Z), and does save or export the remaining characters A through Y.
Can someone please help me understand why?
characters = string.ascii_uppercase
filename = savepath+str(i)+'.png' #outputs as 'C:Users/X/X/X/Z.png'
for i in characters:
#Settings
W, H = (100, 100)
#Image
image = Image.new("RGB", (W, H), "white")
draw = ImageDraw.Draw(image)
offset_w, offset_h = font.getoffset(i)
w, h = draw.textsize(i, font=font)
pos = ((W-w-offset_w)/2, (H-h-offset_h)/2)
#Draw
draw.text(pos, i, "green", font=font)
#Save PNG File
image.save(filename, "PNG", quality = 95)
My guess is that it is looping through all integers but only saving the final integer, instead of saving each individual integer.

Related

Interactive plot to change array values (MATLAB)

N = 500;
pattern = zeros(N,N);
grid on
plot(pattern)
% gets coordinates of modified cells
[x,y] = ginput;
% convert coordinates to integers
X = uint8(x);
Y = uint8(y);
% convert (X,Y) into linear indices
indx = sub2ind([N,N],x,y);
% switch desired cells on (value of 1)
pattern(indx) = 1;
I'm trying to assign several elements of a zeros array the value of 1. Basically I want to create an interactive plot where the user decides what cells he wants to turn on and then save his drawing as a matrix. In Python it's very simple to use the on_click with Matplotlib, but Matlab is weird and I can't find a clear answer. What's annoying is you can't see where you clicked until you save your changes and check the final matrix. You also can't erase a point if you made a mistake.
Moreover I get the following error : Error using sub2ind Out of range subscript. Error in createPattern (line 12) indx = sub2ind([N,N],X,Y);
Any idea how to fix it?
function CreatePattern
hFigure = figure;
hAxes = axes;
axis equal;
axis off;
hold on;
N = 3; % for line width
M = 20; % board size
squareEdgeSize = 5;
% create the board of patch objects
hPatchObjects = zeros(M,M);
for j = M:-1:1
for k = 1:M
hPatchObjects(M - j+ 1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {#OnPatchPressedCallback, M - j+ 1, k});
end
end
Board = zeros(M,M);
playerColours = [1 1 1; 0 0 0];
xlim([squareEdgeSize M*squareEdgeSize]);
ylim([squareEdgeSize M*squareEdgeSize]);
function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
% change FaceColor to player colour
value = Board(rowIndex,colIndex);
if value == 1
set(hObject, 'FaceColor', playerColours(2, :));
Board(rowIndex,colIndex) = 0; % update board
else
set(hObject, 'FaceColor', playerColours(1, :));
Board(rowIndex,colIndex) = 1; % update board
end
end
end
I found this link and modified the code to be able to expand the board and also select cells that have been turned on already to switch them off.
Now I need a way to extract that board value to save the array.

How to expand 2d array (30x20) to 36x60, which is contained in 620x480 2d array?

The start data: 2d array (620x480) is contained image, where shows human face, and 2d array (30x20) which is contained eye image. Face image includes eye image.
How I can expand eye image to 36x60 to include pixels from face image? Are there ready-made solutions?
Another similar task: the eye image have 37x27 size. How I can expand eye image to target(closest to 36x60) size, e.g. 39x65 i.e maintain the aspect ratio required before resizing and then resize to 36x60.
Code for testing (project is available by reference):
import dlib
import cv2 as cv
from imutils.face_utils import shape_to_np
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('res/model.dat')
frame = cv.imread('photo.jpg')
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
img = frame.copy()
dets = detector(gray, 0)
for i, det in enumerate(dets):
shape = shape_to_np(predictor(gray, det))
shape_left_eye = shape[36:42]
x, y, h, w = cv.boundingRect(shape_left_eye)
cv.rectangle(img, (x, y), (x + h, y + w), (0, 255, 0), 1)
cv.imwrite('file.png', frame[y: y+w, x: x+h])
The image 42x13:
For the first part you can use cv2.matchTemplate to find the eye region in the face and then according to the size you want you can enlarge it. You can read more about it here.
FACE IMAGE USED
EYE IMAGE USED
The size of eye I have (12, 32).
face = cv2.imread('face.jpg', 0)
eye = cv2.imread('eye.jpg', 0)
w, h = eye.shape[::-1]
res = cv2.matchTemplate(face,eye,cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(face ,top_left, bottom_right, 255, 2)
cv2.imshow('image', face)
cv2.waitKey(0)
cv2.destroyAllWindows()
The result with this code is:
Now I have the top left and bottom right co-ordinates of the eye that is matched where top_left = (112, 108) and bottom_right = (144, 120). Now to expand them to dimensions of 36x60 I simply subtract the required values from top_left and add the required values in bottom_right.
EDIT 1
The question has been edited which suggests that dlib has been used along with a model trained to perform left eye detection. Using the same code I obtained
After that as proposed above I find top_left = (x,y) and bottom_right = (x+w, y+h).
Now if the eye size is smaller 36x60 then we just have to take the area around it to expand it to 36x60 otherwise we have to expand it as such that the aspect ratio is not disturbed and then resized and it cannot be hard coded. The full code used is:
import dlib
from imutils.face_utils import shape_to_np
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('res/model.dat')
face = cv2.imread('face.jpg', 0)
img = face.copy()
dets = detector(img, 0)
for i, det in enumerate(dets):
shape = shape_to_np(predictor(img, det))
shape_left_eye = shape[36:42]
x, y, w, h = cv2.boundingRect(shape_left_eye)
cv2.rectangle(face, (x, y), (x + w, y + h), (255, 255, 255), 1)
top_left = (x, y)
bottom_right = (x + w, y + h)
if w <= 36 and h <= 60:
x = int((36 - w)/2)
y = int((60 - h)/2)
else:
x1 = w - 36
y1 = h - 60
if x1 > y1:
x = int((w % 3)/2)
req = (w+x) * 5 / 3
y = int((req - h)/2)
else:
y = int((h % 5)/2)
req = (y+h) * 3 / 5
x = int((req - w)/2)
top_left = (top_left[0] - x, top_left[1] - y)
bottom_right = (bottom_right[0] + x, bottom_right[1] + y)
extracted = face[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]
result = cv2.resize(extracted, (36, 60), interpolation = cv2.INTER_LINEAR)
cv2.imshow('image', face)
cv2.imshow('imag', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Which gives us a 36x60 region of the eye:
This takes care of the case when size of eye is smaller than 36x60. For the second case when the size of eye is larger than 36x60 region I used face = cv2.resize(face, None, fx=4, fy=4, interpolation = cv2.INTER_CUBIC). The result was:
The size of eye detected is (95, 33) and the extracted region is (97, 159) which is very close to the aspect ration of 3:5 before resizing which also satisfies that second task.

How to create a grid from 1D array using R?

I have a file which contains a 209091 element 1D binary array representing the global land area
which can be downloaded from here:
ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_flags_2002/
I want to create a full from the 1D data arrays using provided ancillary row and column files .globland_r and globland_c which can be downloaded from here:
ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_ancil/
There is a code written in Matlab for this purpose and I want to translate this Matlab code to R but I do not know Matlab
function [gridout, EASE_r, EASE_s] = mkgrid_global(x)
%MKGRID_GLOBAL(x) Creates a matrix for mapping
% gridout = mkgrid_global(x) uses the 2090887 element array (x) and returns
%Load ancillary EASE grid row and column data, where <MyDir> is the path to
%wherever the globland_r and globland_c files are located on your machine.
fid = fopen('C:\MyDir\globland_r','r');
EASE_r = fread(fid, 209091, 'int16');
fclose(fid);
fid = fopen('C:\MyDir\globland_c','r');
EASE_s = fread(fid, 209091, 'int16');
fclose(fid);
gridout = NaN.*zeros(586,1383);
%Loop through the elment array
for i=1:1:209091
%Distribute each element to the appropriate location in the output
%matrix (but MATLAB is
%(1,1)
end
EDit following the solution of #mdsumner:
The files MLLATLSB and MLLONLSB (4-byte integers) contain latitude and longitude (multiply by 1e-5) for geo-locating the full global EASE grid matrix (586×1383)
MLLATLSB and MLLONLSB can be downloaded from here:
ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_ancil/
## the sparse dims, literally the xcol * yrow indexes
dims <- c(1383, 586)
cfile <- "ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_ancil/globland_c"
rfile <- "ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_ancil/globland_r"
## be nice, don't abuse this
col <- readBin(cfile, "integer", n = prod(dims), size = 2, signed = FALSE)
row <- readBin(rfile, "integer", n = prod(dims), size = 2, signed = FALSE)
## example data file
fdat <- "ftp://sidads.colorado.edu/DATASETS/nsidc0451_AMSRE_Land_Parms_v01/AMSRE_flags_2002/flags_2002170A.bin"
dat <- readBin(fdat, "integer", n = prod(dims), size = 1, signed = FALSE)
## now get serious
m <- matrix(as.integer(NA), dims[2L], dims[1L])
m[cbind(row + 1L, col + 1L)] <- dat
image(t(m)[,dims[2]:1], col = rainbow(length(unique(m)), alpha = 0.5))
Maybe we can reconstruct this map projection too.
flon <- "MLLONLSB"
flat <- "MLLATLSB"
## the key is that these are integers, floats scaled by 1e5
lon <- readBin(flon, "integer", n = prod(dims), size = 4) * 1e-5
lat <- readBin(flat, "integer", n = prod(dims), size = 4) * 1e-5
## this is all we really need from now on
range(lon)
range(lat)
library(raster)
library(rgdal) ## need for coordinate transformation
ex <- extent(projectExtent(raster(extent(range(lon), range(lat)), crs = "+proj=longlat"), "+proj=cea"))
grd <- raster(ncols = dims[1L], nrows = dims[2L], xmn = xmin(ex), xmx = xmax(ex), ymn = ymin(ex), ymx = ymax(ex), crs = "+proj=cea")
There is probably an "out by half pixel" error in there, left as an exercise.
Test
plot(setValues(grd, m), col = rainbow(max(m, na.rm = TRUE), alpha = 0.5))
Hohum
library(maptools)
data(wrld_simpl)
plot(spTransform(wrld_simpl, CRS(projection(grd))), add = TRUE)
We can now save the valid cellnumbers to match our "grd" template, then read any particular dat-file and just populate the template with those values based on cellnumbers. Also, it seems someone trod nearly this path earlier but not much was gained:
How to identify lat and long for a global matrix?

Forming a giant array of multiple 64 x 64 matrices

I am working video shot boundary detection using matlab. Here is my code snippet
clc;
clear all;
[file path] = uigetfile('*.avi','Pick a Video');% this line opens a pop up window so that you can choose your video for further processing
video = VideoReader([path file]);% the video chosen through UI get stored in video object
numOfFrames = video.NumberOfFrames;% this will be a number (total number of frames in your chosen video)
%allFrames = read(video);% catching all the frames from the video in object allFrames
for i=1:1:numOfFrames
try
lFrame = read(video, i);%frames(:, :, :, i);
catch
break;
end
lRFrame = lFrame(:,:,1);
lGFrame = lFrame(:,:,2);
lBFrame = lFrame(:,:,3);
lGray = 0.299*lRFrame + 0.587*lGFrame + 0.114*lBFrame;
grayImage = imresize(lGray, [256 256]);
% step 2 of the algorithm begins from here %
meanFilterFunction = #(theBlockStructure) mean2(theBlockStructure.data(:)) * ones(1,1, class(theBlockStructure.data));
blockSize = [4 4];
blockyImage4 = blockproc(single(grayImage), blockSize, meanFilterFunction);
end
I am getting a 64 x 64 image in blockyImage4 but since it is in a loop , the value flushes itself in very next iteration every time.
I want an array of images which can store (possibly all) images(matrices). and i should have access to them all. if all the images could not be stored in an array then how to store only two images of consecutive iterations since i need 'i' and "i+1" th image to find out the diffrence between them. Please help
You want to store 3D (x,y,time) data in Matlab? Do it either in a cell array or a 3D array. For the array don't forget to preallocate the needed size to avoid performance drops.
So either:
blockyimages = cell(numOfFrames, 1);
for i=1:1:numOfFrames
...
blockyimages{i} = blockproc(single(grayImage), blockSize, meanFilterFunction);
end
% access the blocky image of the ith frame with blockyimages{i}
% you could even do blockyimages = cat(3, blockyimages{:}) to convert to a 3d matrix
or
blockyimages = zeros(64, 64, numOfFrames); % better frame sizes / block sizes
for i=1:1:numOfFrames
...
blockyimages(:, :, i) = blockproc(single(grayImage), blockSize, meanFilterFunction);
end
% access the blocky image of the ith frame with blockyimages(:, :, i)
So, if you chose the second option and later want to do something with the blockyimages again, just make a second pass through the loop. For example if you want to compute the differences of consecutive blockyimages.
diffblockyimages = zeros(64, 64, numOfFrames - 1);
for i = 1 : numOfFrames - 1
framei = blockyimages(:, :, i);
frameiplusone = blockyimages(:, :, i+1);
diffblockyimages(:, :, i) = frameiplusone - framei;
end
Although the same could have been achieved in the special case of the difference also as
diffblockyimages = diff(blockyimages, 1, 3);
Since my comment is blocked I present possible solution:
tested and works fine for me
file_path = uigetfile('*.avi','Pick a Video');% this line opens a pop up window so that you can choose your video for further processing
video = VideoReader(file_path);% the video chosen through UI get stored in video object
numOfFrames = video.NumberOfFrames;% this will be a number (total number of frames in your chosen video)
%allFrames = read(video);% catching all the frames from the video in object allFrames
all_frames = cell(1,numOfFrames);
for i=1:numOfFrames %default step is always 1
try
lFrame = read(video, i);%frames(:, :, :, i);
catch
break;
end
lGray = rgb2gray(lFrame);
grayImage = imresize(lGray, [256 256]);
all_frames{1,i} = grayImage;
end
now you have all frames in all_frames array
access is easy:
img1 = all_frames{1,1}; imshow(img1);
img2 = all_frames{1,2}; imshow(img2);

Lua: how to load a large CSV file into a table and acess it

I'm new at Lua and I can't load a csv file that looks like this :
22.74,22.99,23.47,24.44,26.39,30.27,38.05,53.6,84.7,146.9,271.3,520.1,1017.7,2012.89,4003.28,7984.06,15945.63,31868.75,63715.01,127407.52,254792.53
there are 21 values separated by a comma with no space in the line. I have hundreds of lines. and hundreds of files.
I need to load these lines in a table in Lua and be able to access with simple coordinates (i, j). I would like to call each number cs1, cs2, cs3... cs21 and each line by a number.
I have looked at this function
function readwaypoints(filename, numberofwaypoints)
local file = io.open(filename)
local waypoints = {}
for n = 1, numberofwaypoints do
local x, y, z
x = file:read('*n')
y = file:read('*n')
z = file:read('*n')
waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z}
end
file:close()
return waypoints
end
But it does not seem to work. Or I don't know how to access the data.
Can anyone suggest me a solution to my problem ? Thanks.
It doesn't work because *n expects a number in the input and will skip whitespaces, but not commas. You will need to "eat" commas with file:read(1) or something similar.
function readwaypoints(filename, numberofwaypoints)
local file = io.open(filename)
local waypoints = {}
for n = 1, numberofwaypoints do
local x, y, z
x = file:read('*n'); file:read(1) --<-- added
y = file:read('*n'); file:read(1) --<-- added
z = file:read('*n'); file:read(1) --<-- added
waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z}
end
file:close()
return waypoints
end
local waypoints = readwaypoints("waypoints.txt", 20)
print(waypoints[2].x == 24.44, waypoints[1].z == 23.47)
This prints true true for me. You can access these elements with waypoints[<number of waypoints>].x (or y/z).

Resources